package com.wfcm.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wfcm.entity.*;
import com.wfcm.service.*;
import com.wfcm.utils.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.wfcm.annotation.IgnoreSign;
import com.wfcm.annotation.IgnoreToken;
import com.wfcm.exception.WFCMException;
import com.wfcm.wxPay.MD5Util;
import com.wfcm.wxPay.ResponseHandler;
import com.wfcm.wxPay.WXOrderQuery;
import com.wfcm.wxPay.WXPayUtil;

@Controller
@RequestMapping("/order")
@ResponseBody
public class OrderController {

	private Logger log = LoggerFactory.getLogger(OrderController.class);
	@Autowired
	private WfGoodsOrderService goodsOrderService;
	@Autowired
	private WfGoodsOrderRelationService goodsOrderRelationService ;
	@Autowired
	private WfCoinLogService coinLogService ;
	@Autowired
	private WfMemberCouponsService memberCouponsService ;
	@Autowired
	private WfCourseChapterService courseChapterService;
	@Autowired
	private WfCourseInfoService courseInfoService;
	@Autowired
	private WfVipCardService vipCardService;
	@Autowired
	private WfActivityService activityService;
	@Autowired
	private WfMemberInvitationService invitationService;
	@Autowired
	private WfBillService billService;
	@Autowired
	private WfShoppingCartService shoppingCartService;
	@Autowired
	private WfMemberNewGoldLogService memberNewGoldLogService ;
	@Autowired
	private WfMemberGoldLogService memberGoldLogService ;
	@Autowired
	private WfMemberGiveCoinLogService memberGiveCoinLogService ;
	@Autowired
	private WfRechargeService rechargeService ;
	@Autowired
	private WfMemberRechargeOrderService memberRechargeOrderService;
	@Autowired
	private WfMemberService memberService;
	@Autowired
	private WfCollectionService collectionService;
	@Autowired
	private WfCourseGiftService courseGiftService;
	@Autowired
	private WfCollageOrderService collageOrderService;
	@Autowired
	private DistributionService distributionService;
	@Autowired
	private WfLuckyService luckyService;
	@Autowired
	private WfLuckyCodeService luckyCodeService;
	@Autowired
	private WfNewMessageService newMessageService;
	@Autowired
	private RecordService recordService;

	/**
	 * 个人中心
	 */
	@RequestMapping("/mine")
	@ResponseBody
	public R mine(HttpServletRequest req) {

		Map<String,Object> map =new  HashMap<String,Object>();
		Integer uid = ISsoLoginHelper.confirm(req);
		//获取待付款个数
		map.put("uid", uid);
		//获取已完成个数
		int alreadyPayTotal = goodsOrderService.queryAlreadyPay(map);
		int allTotal = goodsOrderService.queryTotal(map);
		//获取优惠券个数
		int couponsTotal =  memberCouponsService.queryTotal(map);

		map.put("type", 1);//商品类型（1.课程 2.章节3.vip卡4商品）
		int courseCollect = collectionService.queryTotal(map);
		map.put("type", 2);
		int chapterCollect = collectionService.queryTotal(map);
		map.put("type", 3);
		int vipCollect = collectionService.queryTotal(map);

		/*recordService.selectByCreateTime();*/

		//获取已购课程个数
		Map<String,Object> map1 =new  HashMap<String,Object>();
		map1.put("uid", uid);
		map1.put("orderStatus", 4);//订单状态（1.待付款2.待收货3.待评价4.已完成5.取消订单）
		List<WfGoodsOrderEntity>  goodsOrderList = goodsOrderService.queryList(map1);
		List<WfGoodsOrderRelationEntity> goodsCourseList = new ArrayList<WfGoodsOrderRelationEntity>();//获取所有已完成订单
		List<WfGoodsOrderRelationEntity> goodsVipList = new ArrayList<WfGoodsOrderRelationEntity>();//获取所有已完成订单
		for(int i=0 ; i<goodsOrderList.size(); i++) {
			WfGoodsOrderEntity goodsOrderEntity = goodsOrderList.get(i);
			map.put("orderCode",goodsOrderEntity.getOrdercode());
			List<WfGoodsOrderRelationEntity> courseList =  goodsOrderRelationService.queryList(map);//根据订单号获取其中所有课程
			for(int j=0 ; j<courseList.size(); j++) {
				int m = courseList.get(j).getGoodssort();
				if( m == 1||m == 2) {
					goodsCourseList.add(courseList.get(j));
				}else if(m == 3){
					goodsVipList.add(courseList.get(j));
				}
			}
		}

		Map<String,Object> resultMap =new  HashMap<String,Object>();
		resultMap.put("allTotal", allTotal);
		resultMap.put("alreadyPayTotal", alreadyPayTotal);
		resultMap.put("couponsTotal", couponsTotal);
		resultMap.put("courseCollect", courseCollect);
		resultMap.put("chapterCollect", chapterCollect);
		resultMap.put("allCollect", chapterCollect+courseCollect+vipCollect);
		resultMap.put("vipCollect", vipCollect);
		resultMap.put("courseTotal", goodsCourseList.size());
		resultMap.put("vipTotal", goodsVipList.size());
		return R.ok(resultMap);
	}

	/**
	 * 个人中心
	 */
	@RequestMapping("/person")
	@ResponseBody
	public R person(HttpServletRequest req) {

		Map<String,Object> map =new  HashMap<String,Object>();
		Integer uid = ISsoLoginHelper.confirm(req);
		//获取待付款个数
		map.put("uid", uid);
		/*int noPayTotal = goodsOrderService.queryNoPay(map);*/
		//获取已完成个数
		int alreadyPayTotal = goodsOrderService.queryAlreadyPay(map);

		//获取已购课程个数
		/*List<WfGoodsOrderEntity>  goodsOrderList = goodsOrderService.queryByUserId(uid);
		List<WfGoodsOrderRelationEntity> goodsCourseList = new ArrayList<WfGoodsOrderRelationEntity>();//获取所有已完成订单
		for(int i=0 ; i<goodsOrderList.size(); i++) {
			WfGoodsOrderEntity goodsOrderEntity = goodsOrderList.get(i);
			map.put("orderCode",goodsOrderEntity.getOrdercode());
			List<WfGoodsOrderRelationEntity> courseList =  goodsOrderRelationService.queryList(map);//根据订单号获取其中所有课程
			for(int j=0 ; j<courseList.size(); j++) {
				goodsCourseList.add(courseList.get(j));
			}
		}*/

		//获取铜钱总数
		/*List<WfCoinLogEntity> coinLogList =  coinLogService.queryList(map);
		BigDecimal coins = new BigDecimal("0");
		for(int k = 0 ; k< coinLogList.size(); k++) {
			WfCoinLogEntity coinLogEntity = coinLogList.get(k);
			if(1 == coinLogEntity.getFlowflag()) {
				coins = coins.add(coinLogEntity.getCoinvalue());
			}else {
				coins = coins.subtract(coinLogEntity.getCoinvalue());
			}
		}*/

		//获取优惠券个数
		/*int couponsTotal =  memberCouponsService.queryTotal(map);*/

		Map<String,Object> resultMap =new  HashMap<String,Object>();
		/*resultMap.put("noPayTotal", noPayTotal);*/
		resultMap.put("alreadyPayTotal", alreadyPayTotal);
		/*resultMap.put("courseTotal", goodsCourseList.size());*/
		/*resultMap.put("coins", coins.doubleValue());
		resultMap.put("couponsTotal", couponsTotal);*/
		return R.ok(resultMap);
	}

	/**
	 * 恢复购买
	 */
	@RequestMapping("/merge")
	@ResponseBody
	public R merge(HttpServletRequest req) {

		Map<String,Object> map =new  HashMap<String,Object>();
		Integer uid = ISsoLoginHelper.confirm(req);

		String uuid = req.getParameter("uuid");//获取用户唯一标识
		WfMemberEntity  visitor =  memberService.queryByIdentity(uuid);
		Integer vuid = visitor.getUserid();
		map.put("uid", vuid);

		//获取订单
		List<WfGoodsOrderEntity>  goodsOrderList = goodsOrderService.queryByUserId(vuid);
		for(int i=0 ; i<goodsOrderList.size(); i++) {
			WfGoodsOrderEntity goodsOrderEntity = goodsOrderList.get(i);
			goodsOrderEntity.setUserid(uid);
			goodsOrderService.update(goodsOrderEntity);
		}
		List<WfGoodsOrderRelationEntity> goodsCourseList = goodsOrderRelationService.queryList(map);//获取订单关联数据
		for(int m=0 ; m<goodsCourseList.size(); m++) {
			WfGoodsOrderRelationEntity course =  goodsCourseList.get(m);
			course.setUserid(uid);
			goodsOrderRelationService.update(course);
		}

		//获取铜钱总数
		List<WfCoinLogEntity> coinLogList =  coinLogService.queryList(map);
		for(int k = 0 ; k< coinLogList.size(); k++) {
			WfCoinLogEntity coinLogEntity = coinLogList.get(k);
			coinLogEntity.setUserid(uid);
			coinLogService.update(coinLogEntity);
		}

		//金币
		List<WfMemberGoldLogEntity> memberGoldLogList = memberGoldLogService.queryList(map);
		for(int i=0; i<memberGoldLogList.size(); i++) {
			WfMemberGoldLogEntity memberGoldLog = memberGoldLogList.get(i);
			memberGoldLog.setUserid(uid);
			memberGoldLogService.update(memberGoldLog);
		}

		//新金币
		List<WfMemberNewGoldLogEntity> memberNewGoldLogList = memberNewGoldLogService.queryList(map);
		for(int i=0; i<memberNewGoldLogList.size(); i++) {
			WfMemberNewGoldLogEntity memberNewGoldLog = memberNewGoldLogList.get(i);
			memberNewGoldLog.setUserid(uid);
			memberNewGoldLogService.update(memberNewGoldLog);
		}

		//新铜钱
		List<WfMemberGiveCoinLogEntity> memberberGiveCoinLogList = memberGiveCoinLogService.queryList(map);
		for(int i=0; i<memberberGiveCoinLogList.size(); i++) {
			WfMemberGiveCoinLogEntity memberberGiveCoinLog  = memberberGiveCoinLogList.get(i);
			memberberGiveCoinLog.setUserid(uid);
			memberGiveCoinLogService.update(memberberGiveCoinLog);
		}

		//删除游客身份
		//memberService.delete(vuid);

		return R.ok();
	}

	/**
	 * 铜钱交易记录
	 */
	@RequestMapping("/coinlog")
	@ResponseBody
	public R coinlog(HttpServletRequest req) {

		Map<String,Object> map =new  HashMap<String,Object>();
		Integer uid = ISsoLoginHelper.confirm(req);
		//获取待付款个数
		map.put("uid", uid);
		map.put("status", 2);
		List<Map<String,Object>> resultList = new ArrayList<Map<String, Object>>();
		//获取原铜钱
		List<String> monthList =   coinLogService.queryMonth(map);//根据月份分组显示
		for(int i=0; i<monthList.size(); i++) {
			map.put("month", monthList.get(i));
			//map.put("status", 2);
			map.put("deleteFlag", 0);
			List<WfCoinLogEntity> logList =  coinLogService.queryAllList(map);
			Map<String,Object> result =new  HashMap<String,Object>();
			result.put("mouth",  monthList.get(i));
			result.put("logList", logList);
			resultList.add(result);
		}

		Map<String,Object> resultMap = new HashMap<String, Object>();
		resultMap.put("resultList", resultList);

		return R.ok(resultMap);
	}

	/**
	 * 获取活动
	 */
	@RequestMapping("/getActivity")
	@ResponseBody
	public R getActivity(HttpServletRequest req) {
		String price = req.getParameter("price");

		Map<String,Object> resultMap =new  HashMap<String,Object>();

		Map<String,Object> map2 =new  HashMap<String,Object>();
		map2.put("price", price);//总价
		List<WfActivityEntity> activityList = activityService.queryList(map2);
		double dPrice = Double.valueOf(price);
		if(activityList.size()>0) {
			WfActivityEntity  activity= activityList.get(0);//优惠信息：当前满减活动
			int conditionCost = activity.getConditionCost();
			dPrice = dPrice - conditionCost;
			resultMap.put("activity", activity);
		}

		return R.ok(resultMap);
	}

	/**
	 * 去结算(老接口)
	 */
	@RequestMapping("/toCal")
	@ResponseBody
	public R toCal(HttpServletRequest req) {
		Integer uid = ISsoLoginHelper.confirm(req);
		Map<String,Object> map =new  HashMap<String,Object>();
		String price = req.getParameter("price");

		Map<String,Object> resultMap =new  HashMap<String,Object>();

		Map<String,Object> map2 =new  HashMap<String,Object>();
		map2.put("price", price);//总价
		List<WfActivityEntity> activityList = activityService.queryList(map2);
		double dPrice = Double.valueOf(price);
		if(activityList.size()>0) {
			WfActivityEntity  activity= activityList.get(0);//优惠信息：当前满减活动
			int cost = activity.getCost();
			dPrice = dPrice - cost;
			resultMap.put("activity", activity);
		}

		map.put("price", dPrice);//总价
		map.put("out", 2);//是否过期 （1，是；2，否）
		map.put("userId", uid);
		map.put("status", 2);//是否已使用（1是2否）
		List<WfMemberCouponsEntity> couponsList = memberCouponsService.queryList(map);

		//获取铜钱总数
		Map<String,Object> map1 =new  HashMap<String,Object>();
		map1.put("uid", uid);

		List<WfCoinLogEntity> coinLogList =  coinLogService.queryList(map1);
		BigDecimal coins = new BigDecimal("0");
		for(int k = 0 ; k< coinLogList.size(); k++) {
			WfCoinLogEntity coinLogEntity = coinLogList.get(k);
			if(1 == coinLogEntity.getFlowflag() && coinLogEntity.getDeleteflag()==0) {
				coins = coins.add(coinLogEntity.getCoinvalue());
			}else if(2 == coinLogEntity.getFlowflag() && coinLogEntity.getDeleteflag()==0
					&& (coinLogEntity.getStatus()==1 || coinLogEntity.getStatus()==2 )){
				coins = coins.subtract(coinLogEntity.getCoinvalue());
			}
		}
		//查询新铜钱（邀请人消费后赠送的）
		List<WfMemberGiveCoinLogEntity> memberberGiveCoinLogList = memberGiveCoinLogService.queryList(map1);
		for(int i=0; i<memberberGiveCoinLogList.size(); i++) {
			WfMemberGiveCoinLogEntity  memberberGiveCoinLog = memberberGiveCoinLogList.get(i);
			if(1 == memberberGiveCoinLog.getType()||3 == memberberGiveCoinLog.getType()) {
				coins = coins.add(memberberGiveCoinLog.getCoinvalue());
			}else if(2 == memberberGiveCoinLog.getType()
					&& (memberberGiveCoinLog.getStatus()==1 || memberberGiveCoinLog.getStatus()==2 )){
				coins = coins.subtract(memberberGiveCoinLog.getCoinvalue());
			}
		}
		//查询金币充值
		List<WfMemberGoldLogEntity> memberGoldLogList = memberGoldLogService.queryList(map1);
		for(int i=0; i<memberGoldLogList.size(); i++) {
			WfMemberGoldLogEntity   memberGoldLog = memberGoldLogList.get(i);
			if(1 == memberGoldLog.getType() || 3 == memberGoldLog.getType()) {
				coins = coins.add(memberGoldLog.getGoldvalue());
			}else if(2 == memberGoldLog.getType()
					&& (memberGoldLog.getStatus()==1 || memberGoldLog.getStatus()==2 )){
				coins = coins.subtract(memberGoldLog.getGoldvalue());
			}
		}
		//查询新金币充值
		List<WfMemberNewGoldLogEntity> memberNewGoldLogList = memberNewGoldLogService.queryList(map1);
		for(int i=0; i<memberNewGoldLogList.size(); i++) {
			WfMemberNewGoldLogEntity   memberNewGoldLog = memberNewGoldLogList.get(i);
			if(1 == memberNewGoldLog.getType() || 3 == memberNewGoldLog.getType()) {
				coins = coins.add(memberNewGoldLog.getGoldvalue());
			}else if(2 == memberNewGoldLog.getType()
					&& (memberNewGoldLog.getStatus()==1 || memberNewGoldLog.getStatus()==2 )){
				coins = coins.subtract(memberNewGoldLog.getGoldvalue());
			}
		}

		resultMap.put("resultList", couponsList);
		BigDecimal c = new BigDecimal("0.00");
		if(coins.compareTo(c)<0 ) {
			resultMap.put("coins", "0.00");
		}else {
			resultMap.put("coins", coins.setScale(2,BigDecimal.ROUND_HALF_UP));
		}
		return R.ok(resultMap);
	}

	/**
	 * 去结算（新接口）
	 */
	@RequestMapping("/toCalNew")
	@ResponseBody
	public R toCalNew(HttpServletRequest req) {
		Integer uid = ISsoLoginHelper.confirm(req);
		Map<String,Object> map =new  HashMap<String,Object>();
		String price = req.getParameter("price");
		String type = req.getParameter("type");//商品类型（1.课程 2.章节3.vip卡4商品）
		String[] typeArr = type.split(",");
		String foreignId = req.getParameter("foreignId");//商品id(依据商品类型取不同的值)
		String[] foreignIdArr = foreignId.split(",");
		List<String> typeList1 = Arrays.asList(typeArr);//数组转为list
		List<String> typeList = new ArrayList(typeList1);
		List<String> foreignIdList1 = Arrays.asList(foreignIdArr);
		List<String> foreignIdList = new ArrayList(foreignIdList1);

		Map<String,Object> resultMap =new  HashMap<String,Object>();

		Map<String,Object> map2 =new  HashMap<String,Object>();
		map2.put("price", price);//总价
		List<WfActivityEntity> activityList = activityService.queryList(map2);
		double dPrice = Double.valueOf(price);
		if(activityList.size()>0) {
			WfActivityEntity  activity= activityList.get(0);//优惠信息：当前满减活动
			int cost = activity.getCost();
			dPrice = dPrice - cost;
			resultMap.put("activity", activity);
		}

		map.put("price", dPrice);//总价
		map.put("out", 2);//是否过期 （1，是；2，否）
		map.put("userId", uid);
		map.put("status", 2);//是否已使用（1是2否）
		map.put("limits", 1);// 范围（1全场2课程3章节4年卡）
		List<WfMemberCouponsEntity> couponsList = memberCouponsService.queryList(map);

		map.put("out", 2);//是否过期 （1，是；2，否）
		map.put("userId", uid);
		map.put("status", 2);//是否已使用（1是2否）
		List<WfMemberCouponsEntity> couponsLimit = memberCouponsService.queryLimitList(map);//获取指定消费的优惠券
		for (int i = 0; i < couponsLimit.size() ; i++) {
			WfMemberCouponsEntity mc =  couponsLimit.get(i);
			double d = 0.00;
			int flag = -1;//判断是否购买了优惠券中的指定课程
			//或者优惠券中指定课程的总额 start
			for (int j = 0; j < typeArr.length; j++) {
				if(Integer.valueOf(typeArr[j]) == (mc.getLimits()-1)){
					String[] viArr = mc.getValueIds().split(",");
					List<String> viList1 =  Arrays.asList(viArr);
					List<String> viList = new ArrayList(viList1);
					if(viList.contains(foreignIdArr[j])){
						d = d + getPrice(typeList,foreignIdList,j).doubleValue();
						flag = 1;
					}
				}
			}
			//或者优惠券中指定课程的总额 end
			if(flag > 0 && d >= mc.getFtype()){
				couponsList.add(couponsLimit.get(i));
			}
		}

		//获取铜钱总数
		Map<String,Object> map1 =new  HashMap<String,Object>();
		map1.put("uid", uid);
		/*map1.put("status", 2);*/
		List<WfCoinLogEntity> coinLogList =  coinLogService.queryList(map1);
		//查询新铜钱（邀请人消费后赠送的）
		List<WfMemberGiveCoinLogEntity> memberberGiveCoinLogList = memberGiveCoinLogService.queryList(map1);
		//查询金币充值
		List<WfMemberGoldLogEntity> memberGoldLogList = memberGoldLogService.queryList(map1);
		//查询新金币充值
		List<WfMemberNewGoldLogEntity> memberNewGoldLogList = memberNewGoldLogService.queryList(map1);
		BigDecimal coins = getAllOldCoin(coinLogList).add(getAllNewCoin(memberberGiveCoinLogList)).add(getAllGold(memberGoldLogList)).add(getAllNewGold(memberNewGoldLogList));

		resultMap.put("resultList", couponsList);
		BigDecimal c = new BigDecimal("0.00");
		if(coins.compareTo(c)<0 ) {
			resultMap.put("coins", "0.00");
		}else {
			resultMap.put("coins", coins.setScale(2,BigDecimal.ROUND_HALF_UP));
		}
		return R.ok(resultMap);
	}


	/**
	 * 提交订单
	 */
	@RequestMapping("/submitOrder")
	@ResponseBody
	public R submitOrder(HttpServletRequest req,
						 @RequestParam(required = false)String type,
						 @RequestParam(required = false)String foreignId,
						 @RequestParam(required = false)String userSource,
						 @RequestParam(required = false)Double price,
						 @RequestParam(required = false)String couponId,
						 @RequestParam(required = false)String activityId,
						 @RequestParam(required = false)String coinFlag,
						 @RequestParam(required = false)String openid) {
		//商品类型（1.课程 2.章节3.vip卡4商品）,商品id,用户来源（---android/---ios/---h5）,商品总价,优惠券,满减活动,是否使用铜钱（0.否；1.是），微信唯一标识

		Integer uid = ISsoLoginHelper.confirm(req);
		Double totalPrice = price;
		List<String> typeList = strToList(type);//商品类型数组
		List<String> foreignIdList = strToList(foreignId);//商品id数组
		/*int flag = validatePrice(typeList,foreignIdList,price);
		if(flag ==-1){ return R.error(69,"订单金额数据不符，请联系管理员"); }*/

		//课程查重
		for (int j = 0; j < typeList.size(); j++) {
			//判断是否已参加拼团
			Map collageMap = new HashMap<String ,Object>();
			collageMap.put("toUserId",uid);
			collageMap.put("foreignId",foreignId);
			collageMap.put("type",type);
			//获取状态status not in(1,4) 的最新订单
			WfCollageOrderEntity collage = collageOrderService.queryCollaging(collageMap);//获取团单状态；所买课程信息；参团最多人数；
			if(collage!=null){
				return R.error(85,"此课程您已参加拼团，请勿重复购买！");
			}
			int access = -1;
			//商品类型（1.课程 2.章节3.vip卡4商品）
			if ("1".equals(typeList.get(j))) {
				access = checkCourse(uid, Integer.valueOf(foreignIdList.get(j)));
			} else if ("2".equals(typeList.get(j))) {
				access = checkChapter(uid, Integer.valueOf(foreignIdList.get(j)));
			} else if ("3".equals(typeList.get(j))) {
				access = checkVipCard(uid, Integer.valueOf(foreignIdList.get(j)));
			}
			if (access > 0) {
				return R.error(58, "此课程您已经购买！");
			}
		}

		//订单
		WfGoodsOrderEntity order = new WfGoodsOrderEntity();
		String orderNum = DateUtil.getOrderCode();//根据当前时间生成订单号，yyMMddHHmmssSSS + 6位随机数
		order.setOrdercode(orderNum);

		//满减活动
		/*WfActivityEntity activity = null;
		//BigDecimal activityCost = new BigDecimal("0");//满减额度
		if (!("0".equals(activityId))) {//判断是否有满减活动(去结算时，已判断是否符合满减条件)
			activity = activityService.queryObject(Integer.valueOf(activityId));
			price = price - activity.getCost();//满减后的总价
			order.setActivityinfo(activity.getTitle() + ",已减" + activity.getCost() + "元");//优惠信息：满减活动
		}*/

		WfActivityEntity activity = null;
		Map<String,Object> map0 =new  HashMap<String,Object>();
		map0.put("price", price);//总价
		List<WfActivityEntity> activityList = activityService.queryList(map0);
		if(activityList.size()>0) {
			activity= activityList.get(0);//优惠信息：当前满减活动
			price = price - activity.getCost();//满减后的总价
			order.setActivityinfo(activity.getTitle() + ",已减" + activity.getCost() + "元");//优惠信息：满减活动
		}

		//获取用户选择的优惠券
		int cost = 0;
		WfMemberCouponsEntity memberCoupons = null;
		if (!("0".equals(couponId))) {//判断用户是否使用优惠券
			memberCoupons = memberCouponsService.queryObject(Integer.valueOf(couponId));//获取用户选择的优惠券
			if (memberCoupons.getFtype() > price) { return R.error("优惠券未到达满减条件"); }
			cost = memberCoupons.getCost();
			price = price - cost;//抵扣优惠券后的金额
			if (price < 0) { price = 0.0; }//若优惠券抵扣金额大于消费金额，则支付为0
			order.setCouponsMemo("使用" + memberCoupons.getTitle() + "抵扣[" + memberCoupons.getCost() + "]元");
		}

		BigDecimal zero = BigDecimal.ZERO;
		BigDecimal bigPrice = BigDecimal.valueOf(price);//支付总金额（已减去优惠券和满减）
		BigDecimal coinvalue=zero, newcoinvalue=zero, goldvalue=zero, newGoldvalue=zero;//原铜钱消耗值,新铜钱消耗值,金币消耗值

		WfCoinLogEntity coinLog = new WfCoinLogEntity();//原铜钱
		WfMemberGiveCoinLogEntity memberGiveCoinLog = new WfMemberGiveCoinLogEntity();//新铜钱
		WfMemberGoldLogEntity memberGoldLog = new WfMemberGoldLogEntity();////金币
		WfMemberNewGoldLogEntity memberNewGoldLog = new WfMemberNewGoldLogEntity();////金币

		if ("1".equals(coinFlag)) {//若选择铜钱支付,则扣除顺序：老铜钱->新铜钱->金币
			//a.老铜钱消耗
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("uid", uid);
			BigDecimal mycoins = getAllOldCoin(coinLogService.queryList(map));//我的铜钱
			if ((bigPrice.compareTo(mycoins)) <= 0) {//支付金额 <= 原铜钱
				coinvalue = bigPrice; //原铜钱的消耗 == 支付总金额
				bigPrice = zero; //待支付金额 == 0
			} else {
				//b.新铜钱消耗
				coinvalue = mycoins;//原铜钱消费完
				bigPrice = bigPrice.subtract(mycoins.setScale(2, BigDecimal.ROUND_HALF_UP));//支付总金额-原铜钱=待支付金额
				mycoins = getAllNewCoin(memberGiveCoinLogService.queryList(map));//新铜钱总值
				if (bigPrice.compareTo(mycoins) <= 0) {//待支付金额 <= 新铜钱总值
					newcoinvalue = bigPrice;//新铜钱消耗值
					bigPrice = zero;//待支付金额为零
				} else {
					//c.金币消耗
					newcoinvalue = mycoins;//新铜钱消耗完
					bigPrice = bigPrice.subtract(mycoins.setScale(2, BigDecimal.ROUND_HALF_UP));//支付总金额-原铜钱-新铜钱=待支付金额
					mycoins = getAllGold(memberGoldLogService.queryList(map));//查询金币总值
					if (bigPrice.compareTo(mycoins) <= 0) {//待支付金额 <= 金币
						goldvalue = bigPrice;//金币消耗值
						bigPrice = zero;//待支付金额为零
					} else {
						//d.新金币消耗
						goldvalue = mycoins;//金币消耗完
						bigPrice = bigPrice.subtract(mycoins.setScale(2, BigDecimal.ROUND_HALF_UP));//支付总金额-原铜钱-新铜钱-金币=待支付金额
						mycoins = getAllNewGold(memberNewGoldLogService.queryList(map));//查询新金币总值
						if (bigPrice.compareTo(mycoins) <= 0) {//待支付金额 <= 新金币
							newGoldvalue = bigPrice;//新金币消耗值
							bigPrice = zero;//待支付金额为零
						} else {
							newGoldvalue = mycoins;//新金币消耗完
							bigPrice = bigPrice.subtract(mycoins.setScale(2, BigDecimal.ROUND_HALF_UP));//支付总金额-原铜钱-新铜钱-新金币=待支付金额
						}
					}
				}
			}
			//保存原铜钱，新铜钱，金币消耗记录
			if (coinvalue.compareTo(zero) != 0) {//flowflag流向标识（1.赚 2.花）; Resource来源或用途（1.购物 2.邀请好友 3.充值）; Status状态（1审核中2成功）   ; Deleteflag(0.未删除1.已删除)
				coinLog.setAll(uid,0,2,coinvalue,"1",orderNum,1,new Date(),0);
				coinLogService.save(coinLog);
			}
			order.setCoppercash("使用铜钱抵扣" + coinvalue.add(newcoinvalue).add(goldvalue) + "元");//消耗的原铜钱
			if (newcoinvalue.compareTo(zero) > 0) {//status(1,进行中;2，完成), type(1,赚;2,花) , newcoinvalue(消耗的新铜钱)
				memberGiveCoinLog.setAll(uid,newcoinvalue,orderNum,1,new Date(),2,1,null);
				memberGiveCoinLogService.save(memberGiveCoinLog);
			}
			order.setNewcoppercash(newcoinvalue);//消耗的新铜钱
			if (goldvalue.compareTo(zero) > 0) {//status(1,进行中;2,完成) , type(1,赚;2,花),  goldvalue 消耗的金币
				memberGoldLog.setAll(uid,goldvalue,orderNum,1,new Date(),2,userSource);
				memberGoldLogService.save(memberGoldLog);
			}
			order.setGold(goldvalue);//消耗的金币
			if (newGoldvalue.compareTo(zero) > 0) {//status(1,进行中;2,完成) , type(1,赚;2,花),  newGoldvalue 消耗的新金币
				memberNewGoldLog.setAll(uid,newGoldvalue,orderNum,1,new Date(),2,userSource);
				memberNewGoldLogService.save(memberNewGoldLog);
			}
			order.setNewGold(newGoldvalue);//消耗的新金币
		}else{
			order.setCoppercash("0");//消耗的原铜钱
			order.setNewcoppercash(zero);//消耗的新铜钱
			order.setGold(zero);//消耗的金币
			order.setNewGold(zero);//消耗的新金币
		}
		order.setOrdertime(new Date());
		order.setPaytype(1);//1、微信支付
		order.setUserid(uid);  //order.setRecipient("");//接收人
		order.setUsersource(userSource);
		order.setCouponsId(Integer.valueOf(couponId));
		order.setGoodsamount(BigDecimal.valueOf(totalPrice));//商品总金额
		order.setOrderamount(bigPrice);//微信支付金额
		order.setOldcoppercash(coinvalue);//老铜钱
		order.setSpendcoin(coinvalue.add(newcoinvalue).add(goldvalue).add(newGoldvalue));//订单花费铜钱数
		order.setVersion("3.0");
		order.setOrdertime(new Date());

		//查找买一增一活动 start
		List<WfCourseGiftEntity> courseGiftList = courseGiftService.queryList(null);
		List<String> stringList = new ArrayList<>();
		if (courseGiftList.size()>0) {
			for (int i = 0; i < courseGiftList.size(); i++) {
				int courseType = courseGiftList.get(i).getType();
				int courseid = courseGiftList.get(i).getCourseId();
				for (int j = 0; j < typeList.size(); j++) {
					if (courseType == Integer.valueOf(typeList.get(j)) && courseid == Integer.valueOf(foreignIdList.get(j))) {//如果买的课程属于买一增一的活动内容，则赠课
						int giftCourseId = courseGiftList.get(i).getGiftCourseId();//赠送课程id
						int giftType = courseGiftList.get(i).getGiftType();//赠送课程类型
						int access = 0;
						if (giftType == 1) {//检查赠送课程是否已经购买过，若已购买，则不再赠送
							access = checkCourse(uid, giftCourseId);
						} else if (giftType == 2) {
							access = checkChapter(uid, giftCourseId);
						} else if (giftType == 3) {
							access = checkVipCard(uid, giftCourseId);
						}
						if (1 != access) {
							//typeList.add("[5]" + giftCourseId);//type =[5] 赠送
							stringList.add("[5]" + giftType); //记录赠送的课程类型
							foreignIdList.add(String.valueOf(giftCourseId));//数组后增加一位元素
						}
					}
				}
			}
		}
		if(stringList.size()>0){
			for (int j = 0; j < stringList.size(); j++) {
				typeList.add(stringList.get(j));//将赠送的课程增加到集合里
			}
		}
		//查找买一增一活动 end


		BigDecimal[] couponsArr =  new BigDecimal[typeList.size()];//获取指定优惠券的抵扣数组
		if(null!=memberCoupons && memberCoupons.getLimits() !=1 ){
			couponsArr = getLimitCouponsPrice(typeList, foreignIdList, memberCoupons);
		}
		double[] percentArr = getEveryPercent(typeList,foreignIdList,memberCoupons,couponsArr);//获取商品数组的价格和总和

		if(bigPrice.compareTo(zero) == 0) {//若微信支付金额为零，保存订单，状态为支付成功
			//优惠券
			if(!"0".equals(couponId)) {
				memberCoupons.setStatus(1);//将用户券状态改为已使用
				memberCouponsService.update(memberCoupons);
			}
			//订单-课程关系表保存
			WfGoodsOrderRelationEntity goodsOrderRelation = new WfGoodsOrderRelationEntity();
			for(int j=0; j<typeList.size(); j++) {
				//商品类型（1.课程 2.章节3.vip卡4商品）
				if("1".equals(typeList.get(j))||"2".equals(typeList.get(j))||"3".equals(typeList.get(j))) {
					goodsOrderRelation.setAllCash(Integer.valueOf(foreignIdList.get(j)),
							getPrice(typeList,foreignIdList,j),
							Integer.valueOf(typeList.get(j)),
							activity == null ? BigDecimal.ZERO :    new BigDecimal(activity.getCost()).multiply(new BigDecimal(percentArr[j])).setScale(2,BigDecimal.ROUND_HALF_UP),
							coinvalue== zero ? BigDecimal.ZERO :    coinvalue.multiply(new BigDecimal(percentArr[j])).setScale(2,BigDecimal.ROUND_HALF_UP),
							newcoinvalue==zero ? BigDecimal.ZERO :  newcoinvalue.multiply(new BigDecimal(percentArr[j])).setScale(2,BigDecimal.ROUND_HALF_UP),
							goldvalue== zero ? BigDecimal.ZERO :    goldvalue.multiply(new BigDecimal(percentArr[j])).setScale(2,BigDecimal.ROUND_HALF_UP),
							newGoldvalue==zero ? BigDecimal.ZERO :  newGoldvalue.multiply(new BigDecimal(percentArr[j])).setScale(2,BigDecimal.ROUND_HALF_UP));

					goodsOrderRelation.setRealpay(zero);//微信消费
					if(memberCoupons == null ||  memberCoupons.getLimits() == 1) {
						goodsOrderRelation.setCouponscash(cost==0 ? BigDecimal.ZERO : new BigDecimal(cost).multiply(new BigDecimal(percentArr[j])).setScale(2,BigDecimal.ROUND_HALF_UP));
					}else if((memberCoupons.getLimits()-1)==Integer.valueOf(typeList.get(j)) && memberCoupons.getValueIds().contains(foreignIdList.get(j))){//若有优惠券对某课程有效
                        goodsOrderRelation.setCouponscash(couponsArr[j]);
                    }else{//有指定优惠券，但优惠券对此课无作用
                        goodsOrderRelation.setCouponscash(zero);
                    }
					Map<String,Object> map1 =new  HashMap<String,Object>();
					map1.put("userId", uid);
					map1.put("foreignId", foreignIdList.get(j));
					map1.put("type", typeList.get(j));
					shoppingCartService.deleteGoods(map1);//清空购物车
				}else if( typeList.get(j).contains("[5]")){//赠送课程type为5  所有费用为0
					goodsOrderRelation.setAllCash(Integer.valueOf(foreignIdList.get(j)),zero, Integer.valueOf(typeList.get(j).substring(3)), zero, zero, zero, zero,zero);
					goodsOrderRelation.setRealpay(zero);//微信消费
					goodsOrderRelation.setCouponscash(zero);
				}
				goodsOrderRelation.setPart(orderNum,1,0,2,0,coinvalue,"3.0",uid,new Date(),4);//Isevaluate是否评价（1是2否）; Backflag是否退货(0.否 1.是)
				goodsOrderRelationService.save(goodsOrderRelation);//保存
			}

			order.setOrderstatus(4);//订单状态（1.待付款2.待收货3.待评价4.已完成5.取消订单）
			order.setOrderpaytime(new Date());
			goodsOrderService.save(order);//支付成功
			//若有抽奖活动，则进行信息通知（抽奖码消息，抽奖码保存）
			if(activity!=null){
				totalPrice = totalPrice - activity.getCost();}//满减后的总价
			List<WfLuckyEntity> list = luckyService.queryList(totalPrice.intValue());
			if(list.size()>0){
				String code = "";
				if(list.get(0).getId()==1){
					code = "WA-"+ uid + "-"+ getStringRandom(4);
				}else if(list.get(0).getId()==2){
					code = "IP-"+ uid + "-"+ getStringRandom(4);
				}if(list.get(0).getId()==3){
					code = "XR-"+ uid + "-"+ getStringRandom(4);
				}
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				WfNewMessageEntity newMessageEntity  = new WfNewMessageEntity(uid,null,4,0,"抽奖活动提醒","恭喜您获取了活动本次抽奖活动的抽奖码！！！",new Date(),null,null,
						"&nbsp;&nbsp;【好芳法课堂】尊敬的用户，因您在本平台消费满"+list.get(0).getTarget()+"元，获得奖品<strong>"+list.get(0).getGood()+"</strong>的抽奖码一个：<strong>"+code+"</strong>。活动将于"+ sdf.format(list.get(0).getEndtime())+"结束，抽奖结果将于"+list.get(0).getLuckyday()+"前公布。<br/>&nbsp;&nbsp;请您保存此条信息，关注微信公众号：<strong>好芳法课堂</strong>，第一时间获得最新活动消息。");
				newMessageService.save(newMessageEntity);
				WfMemberEntity memberEntity = memberService.queryObject(uid);
				WfLuckyCodeEntity luckyCodeEntity = new WfLuckyCodeEntity(uid,memberEntity.getTelephone(),new Date(),list.get(0).getId(),memberEntity.getUsername(),list.get(0).getGood(),memberEntity.getHeadimage(),new BigDecimal(totalPrice));
				luckyCodeService.save(luckyCodeEntity);
				SendPhoneMessage.sendMes(memberEntity.getTelephone(),String.valueOf(list.get(0).getTarget()),list.get(0).getGood(),code,sdf.format(list.get(0).getEndtime()),list.get(0).getLuckyday());
			}
		}else {
			R  result = new R();
			JSONObject res = null;
			//调用微信下订单接口
			try {
				order.setOrderstatus(1);//订单状态（1.待付款2.待收货3.待评价4.已完成5.取消订单）
				//锁定优惠券
				if(!"0".equals(couponId)) {
					memberCoupons.setStatus(1);//将用户券状态改为已使用
					memberCouponsService.update(memberCoupons);
				}
				//订单-课程关系表  //清空购物车
				WfGoodsOrderRelationEntity goodsOrderRelation = new WfGoodsOrderRelationEntity();
				for(int j=0; j<typeList.size(); j++) {//商品类型（1.课程 2.章节3.vip卡4商品）
					if("1".equals(typeList.get(j))||"2".equals(typeList.get(j))||"3".equals(typeList.get(j))) {
						goodsOrderRelation.setAllCash(Integer.valueOf(foreignIdList.get(j)),
								getPrice(typeList,foreignIdList,j),
								Integer.valueOf(typeList.get(j)),
								activity == null ? BigDecimal.ZERO :    new BigDecimal(activity.getCost()).multiply(new BigDecimal(percentArr[j])).setScale(2,BigDecimal.ROUND_HALF_UP),
								coinvalue== zero ? BigDecimal.ZERO :    coinvalue.multiply(new BigDecimal(percentArr[j])).setScale(2,BigDecimal.ROUND_HALF_UP),
								newcoinvalue==zero ? BigDecimal.ZERO :  newcoinvalue.multiply(new BigDecimal(percentArr[j])).setScale(2,BigDecimal.ROUND_HALF_UP),
								goldvalue== zero ? BigDecimal.ZERO :    goldvalue.multiply(new BigDecimal(percentArr[j])).setScale(2,BigDecimal.ROUND_HALF_UP),
								newGoldvalue==zero ? BigDecimal.ZERO :  newGoldvalue.multiply(new BigDecimal(percentArr[j])).setScale(2,BigDecimal.ROUND_HALF_UP));
						goodsOrderRelation.setRealpay(bigPrice.multiply(new BigDecimal(percentArr[j])).setScale(2,BigDecimal.ROUND_HALF_UP));//微信消费
						if(memberCoupons == null ||  memberCoupons.getLimits() == 1) {
							goodsOrderRelation.setCouponscash(cost==0 ? BigDecimal.ZERO : new BigDecimal(cost).multiply(new BigDecimal(percentArr[j])).setScale(2,BigDecimal.ROUND_HALF_UP));
						}else if((memberCoupons.getLimits()-1)==Integer.valueOf(typeList.get(j)) && memberCoupons.getValueIds().contains(foreignIdList.get(j))){//若有优惠券对某课程有效
							goodsOrderRelation.setCouponscash(couponsArr[j]);
                        }else{//有指定优惠券，但优惠券对此课无作用
							goodsOrderRelation.setCouponscash(zero);
						}
						Map<String,Object> map1 =new  HashMap<String,Object>();
						map1.put("userId", uid);
						map1.put("foreignId", foreignIdList.get(j));
						map1.put("type", 1);
						shoppingCartService.deleteGoods(map1);
					}else if( typeList.get(j).contains("[5]")){//赠送课程type为5  所有费用为0
						goodsOrderRelation.setAllCash(Integer.valueOf(foreignIdList.get(j)),zero, Integer.valueOf(typeList.get(j).substring(3)), zero, zero, zero, zero,zero);
						goodsOrderRelation.setRealpay(zero);//微信消费
						goodsOrderRelation.setCouponscash(zero);
					}
					goodsOrderRelation.setPart(orderNum,1,0,2,0,coinvalue,"3.0",uid,new Date(),1);//Isevaluate是否评价（1是2否）; Backflag是否退货(0.否 1.是)
					goodsOrderRelationService.save(goodsOrderRelation);//保存
				}
				goodsOrderService.save(order);//保存订单
				if(userSource.equals("---ios")||userSource.equals("---android")){
					res = goodsOrderService.dopay(req,orderNum,bigPrice,1);//1，微信支付
				}else{
					/*WfMemberEntity member =  memberService.queryObject(uid);
					if(null!=member.getWxopenid()){
						openid = member.getWxopenid();
					}*/
					res = goodsOrderService.ggdopay(req,orderNum,bigPrice,1,openid);//1，微信支付
				}
				result.putAll(res);
				result.put("orderNum", orderNum);
				return result;//返回json
			} catch (Exception e) {
				log.error("支付异常", e);
				if(e instanceof WFCMException){
					WFCMException ze = (WFCMException)e;
					result=R.error(ze.getErrCode(), ze.getMsg());
					return result;
				}else{
					return R.error();
				}
			}
		}
		//铜钱支付走的流程：支付成功后，课程销量增加，优惠券减少，铜钱余额减少，订单状态为已完成，铜钱奖励邀请人
		//课程销量
		for(int j=0; j<typeList.size(); j++) {//增加所购买商品的销量
			Map<String,Object> map1 =new  HashMap<String,Object>();
			//商品类型（1.课程 2.章节3.vip卡4商品）
			if("1".equals(typeList.get(j))) {
				WfCourseInfoEntity courseInfo = courseInfoService.queryObjectIgnoreStatus(Integer.valueOf(foreignIdList.get(j)));
				int salenum = courseInfo.getCoursesalenumber() + 1;
				courseInfo.setCoursesalenumber(salenum);
				courseInfoService.update(courseInfo);
			}else if("2".equals(typeList.get(j))){
				WfCourseChapterEntity courseChapter = courseChapterService.queryObjectIgnoreStatus(Integer.valueOf(foreignIdList.get(j)));
				int salenum = courseChapter.getChaptersalenumber() + 1;
				courseChapter.setChaptersalenumber(salenum);
				courseChapterService.update(courseChapter);
			}else if("3".equals(typeList.get(j))){
				WfVipCardEntity vipCard = vipCardService.queryObject(Integer.valueOf(foreignIdList.get(j)));
				int salenum = vipCard.getCardsalenumber() + 1;
				vipCard.setCardsalenumber(salenum);
				vipCardService.update(vipCard);
			}
		}

//		//优惠券和铜钱的奖励
//		Map<String,Object> map2 =new  HashMap<String,Object>();
//		map2.put("uid", uid);
//		map2.put("orderStatus",4);
//		List<WfGoodsOrderEntity>  goodsOrderList =  goodsOrderService.queryList(map2);
//		//List<WfMemberGoldLogEntity>  memberGoldLogList = memberGoldLogService.queryList(map2);//查询用户的充值订单和购物订单，判断是否是第一次消费
//		if(1==(goodsOrderList.size())) {//判断是否是第一次购课
//			//优惠券和铜钱的奖励
//			Map<String,Object> map3 =new  HashMap<String,Object>();
//			map3.put("invitedId", uid);
//			List<WfMemberInvitationEntity> invitationList = invitationService.queryList(map3);
//			if(invitationList.size() == 1) {//若是用户第一次消费，且有邀请人，则奖励邀请人其实际支付费用的5%
//				int inviterid = invitationList.get(0).getInviterid();//邀请人id
//				WfMemberGiveCoinLogEntity reward =  new WfMemberGiveCoinLogEntity();//奖励
//				reward.setUserid(inviterid);
//				reward.setTouserid(uid);
//				reward.setType(1);//1.赚 2.花
//				reward.setStatus(2);//1审核中2成功
//				reward.setCoinvalue(new BigDecimal(goldvalue.doubleValue()*5/100));//用户支付金额的5%
//				reward.setCreatetime(new Date());
//				reward.setOrdercode(orderNum);
//				//reward.setRemarkinfo("");
//				memberGiveCoinLogService.save(reward);
//			}
//		}

		// 优惠券和铜钱的奖励
		Map<String, Object> map2 = new HashMap<>(), map3 = new HashMap<>(), map4 = new HashMap<>();
		map2.put("uid", uid);
		map2.put("orderStatus", 4);
		map3.put("invitedId", uid);
		map4.put("orderCode", orderNum);
		Distribution distribution = distributionService.configuration();
		List<WfGoodsOrderEntity> goodsOrderList = goodsOrderService.queryList(map2);
		List<WfMemberInvitationEntity> invitationList = invitationService.queryList(map3);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.add(Calendar.DATE, -distribution.getNum());
		if (invitationList.size() > 0) {
			WfMemberInvitationEntity invitation = invitationList.get(0);
			// 如果邀请关系没过期
			if (calendar.getTime().getTime() <= invitationList.get(0).getCreatetime().getTime()) {
				goodsOrderRelationService.queryList(map4).forEach(item -> {
					if (distributionService.searchGoods(item.getGoodsid(), item.getGoodssort())) {
						BigDecimal decimal = new BigDecimal(0);
						Integer commissionRate = distributionService.searchGoodsInfo
								(item.getGoodsid(), item.getGoodssort()).getCommissionRate();
						decimal = decimal.add(item.getOldcoppercash() != null ? item.getOldcoppercash() : new BigDecimal(0))
								.add(item.getNewcoppercash() != null ? item.getNewcoppercash() : new BigDecimal(0))
								.add(item.getGold() != null ? item.getGold() : new BigDecimal(0))
								.add(item.getRealpay() != null ? item.getRealpay() : new BigDecimal(0))
								.add(item.getNewGold() != null ? item.getNewGold() : new BigDecimal(0))
								.multiply(new BigDecimal(commissionRate)).divide(new BigDecimal(100));
						WfMemberGiveCoinLogEntity reward = new WfMemberGiveCoinLogEntity();
						reward.setUserid(invitation.getInviterid());
						reward.setTouserid(uid);
						reward.setType(1); // 1 赚 2 花
						reward.setStatus(2); // 1 审核中 2 成功
						reward.setSource(2);
						reward.setCoinvalue(decimal);
						reward.setCreatetime(new Date());
						reward.setOrdercode(orderNum);
						reward.setRemarkinfo("邀请用户买课赠送铜钱");
						memberGiveCoinLogService.save(reward);
						Long time = System.currentTimeMillis() / 1000;
						distributionService.addRecord(new Distribution(invitation.getInviterid(), uid, orderNum, decimal.doubleValue(),
								1, time.intValue(), time.intValue(), item.getGoodsid(), item.getGoodssort(), commissionRate));
					}
				});
			} else if (goodsOrderList.size() == 1) {
				// 邀请关系过期，首单返还。
				goodsOrderRelationService.queryList(map4).forEach(item -> {
					BigDecimal decimal = new BigDecimal(0);
					Integer commissionRate = distribution.getCommissionRate();
					decimal = decimal.add(item.getOldcoppercash() != null ? item.getOldcoppercash() : new BigDecimal(0))
							.add(item.getNewcoppercash() != null ? item.getNewcoppercash() : new BigDecimal(0))
							.add(item.getGold() != null ? item.getGold() : new BigDecimal(0))
							.add(item.getRealpay() != null ? item.getRealpay() : new BigDecimal(0))
							.add(item.getNewGold() != null ? item.getNewGold() : new BigDecimal(0))
							.multiply(new BigDecimal(commissionRate)).divide(new BigDecimal(100));
					WfMemberGiveCoinLogEntity reward = new WfMemberGiveCoinLogEntity();
					reward.setUserid(invitation.getInviterid());
					reward.setTouserid(uid);
					reward.setType(1); // 1 赚 2 花
					reward.setStatus(2); // 1 审核中 2 成功
					reward.setSource(2);
					reward.setCoinvalue(decimal);
					reward.setCreatetime(new Date());
					reward.setOrdercode(orderNum);
					reward.setRemarkinfo("邀请用户买课首单赠送铜钱");
					memberGiveCoinLogService.save(reward);
					Long time = System.currentTimeMillis() / 1000;
					distributionService.addRecord(new Distribution(invitation.getInviterid(), uid, orderNum, decimal.doubleValue(),
							1, time.intValue(), time.intValue(), item.getGoodsid(), item.getGoodssort(), commissionRate));
				});
			}
		}

		//原铜钱余额
		if(coinLog != null) {
			coinLog.setStatus(2);//成功
			coinLogService.update(coinLog);
		}

		//新铜钱余额
		if(memberGiveCoinLog != null) {
			memberGiveCoinLog.setStatus(2);//成功
			memberGiveCoinLogService.update(memberGiveCoinLog);
		}

		//金币
		if(memberGoldLog != null) {
			memberGoldLog.setStatus(2);//成功
			memberGoldLogService.update(memberGoldLog);
		}

		//新金币
		if(memberNewGoldLog != null) {
			memberNewGoldLog.setStatus(2);//成功
			memberNewGoldLogService.update(memberNewGoldLog);
		}

		//微信支付成功后订单状态为已完成
		Map<String,Object> resultMap =new  HashMap<String,Object>();
		//resultMap.put("orderNum", orderNum);
		resultMap.put("oldcoppercash", coinvalue.setScale(2,BigDecimal.ROUND_HALF_UP));
		resultMap.put("newcoppercash", newcoinvalue.setScale(2,BigDecimal.ROUND_HALF_UP));
		resultMap.put("gold", goldvalue.setScale(2,BigDecimal.ROUND_HALF_UP));
		resultMap.put("newGold", newGoldvalue.setScale(2,BigDecimal.ROUND_HALF_UP));
		resultMap.put("totalCoin",coinvalue.add(newcoinvalue).add(goldvalue).add(newGoldvalue).setScale(2,BigDecimal.ROUND_HALF_UP));//消耗总铜钱
		resultMap.put("price", price);
		resultMap.put("totalPrice", totalPrice);
		if(!("0".equals(couponId))) {
			resultMap.put("couponsCost", memberCoupons.getCost());
		}else {
			resultMap.put("couponsCost", 0);
		}
		resultMap.put("weChat", 0);
		return R.ok(resultMap);
	}

	/**
	 * 待付款直接支付
	 */
	@RequestMapping("/toPay")
	@ResponseBody
	public R toPay(HttpServletRequest req) {

		Integer uid = ISsoLoginHelper.confirm(req);
		String orderNum = req.getParameter("orderNum");//订单号*****
		String openid = req.getParameter("openid");//微信唯一标识

		WfGoodsOrderEntity  goodsOrder = goodsOrderService.queryByOrderCode(orderNum);
		R  result = new R();
		JSONObject res = null;
		//调用微信下订单接口
		try {
			if(openid != null){
				res = goodsOrderService.ggdopay(req,orderNum,goodsOrder.getOrderamount(),1,openid);//1，微信支付
			}else{
				res = goodsOrderService.dopay(req, orderNum, goodsOrder.getOrderamount(), 1);//1，微信支付
			}
			result.putAll(res);
			result.put("orderNum", orderNum);
			return result;//返回json
		} catch (Exception e) {
			log.error("支付异常", e);
			if(e instanceof WFCMException){
				WFCMException ze = (WFCMException)e;
				result=R.error(ze.getErrCode(), ze.getMsg());
				return result;
			}else{
				return R.error();
			}
		}
	}

	/**
	 * 去充值
	 */
	@RequestMapping("/toRecharge")
	@ResponseBody
	public R toRecharge(HttpServletRequest req) {
		R  result = new R();
		Distribution d = distributionService.queryDistributionByKey("recharge_flag");
		if(d.getValue()==0){
			result.put("orderNum", "1");
			return result;//返回json
		}

		Integer uid = ISsoLoginHelper.confirm(req);
		String price = req.getParameter("price");
		String openid = req.getParameter("openid");//微信唯一标识
		BigDecimal orderAmout = new BigDecimal(price);//支付费用
		String orderNum = "";
		if(null != openid){
			System.out.println("OPENID:"+openid);
			orderNum = DateUtil.getWxRechargeOrderNum(String.valueOf(uid),"wxr");//根据当前时间生成订单号，yyMMddHHmmssSSS + 0~1000000随机数
		}else {
			orderNum = DateUtil.getWxRechargeOrderNum(String.valueOf(uid),"adr");
		}

		JSONObject res = null;
		//调用微信下订单接口
		try {
			if(null != openid){
				System.out.println("OPENID:"+openid);
				res = goodsOrderService.ggdopay(req,orderNum,orderAmout,1,openid);//1，微信支付
			}else {
				res = goodsOrderService.dopay(req,orderNum,orderAmout,1);//1，微信支付
			}
			result.putAll(res);
			result.put("orderNum", orderNum);
			return result;//返回json
		} catch (Exception e) {
			log.error("支付异常", e);
			if(e instanceof WFCMException){
				WFCMException ze = (WFCMException)e;
				result=R.error(ze.getErrCode(), ze.getMsg());
				return result;
			}else{
				return R.error();
			}
		}
	}


	/**
	 * 微信回调
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "wechatreceive")
	@IgnoreSign
	@IgnoreToken
	@ResponseBody
	public void wechatreceive(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ResponseHandler resHandler = new ResponseHandler(request, response);
		try {
			log.info("微信支付==进入==");
			InputStream inStream = request.getInputStream();
			ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
			resHandler.setKey(ConstantUtil.APP_KEY);
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = inStream.read(buffer)) != -1) {
				outSteam.write(buffer, 0, len);
			}
			response.setHeader("ContentType", "text/xml");
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			outSteam.close();
			inStream.close();

			String result = new String(outSteam.toByteArray(), "utf-8");// 获取微信调用我们notify_url的返回信息
			log.info("微信支付==result==" + result);
			Map<Object, Object> map = XMLUtil.doXMLParse(result);
			log.info("微信支付==map==" + map);

			String result_code = "";
			String out_trade_no = "";
			String trade_no = "";
			String total_fee ="";
			String time_end ="";
			for (Object keyValue : map.keySet()) {
				result_code = map.get("result_code").toString();//业务结果
				out_trade_no = map.get("out_trade_no").toString();//商户订单号
				trade_no = map.get("transaction_id").toString();//微信支付订单号
				total_fee = map.get("total_fee").toString();//总金额
				time_end = map.get("time_end").toString();//支付完成时间
			}

			WfGoodsOrderEntity  goodsOrder = goodsOrderService.queryByOrderCode(out_trade_no);

			// 判断
			if(!WXPayUtil.isSignatureValid(result,ConstantUtil.APP_KEY)){
				log.info("微信验签失败");
				resHandler.sendToCFT("FAIL");
			}
			if ("SUCCESS".equals(result_code) ) {
				//支付成功后，课程销量增加，优惠券减少，铜钱余额减少，订单状态为已完成，铜钱奖励邀请人
				Map<String,Object> map1 =new  HashMap<String,Object>();
				map1.put("orderCode", out_trade_no);
				/*WfMemberRechargeOrderEntity memberRechargeOrder = memberRechargeOrderService.queryByOrderNum(map1);*///根据订单号获取充值数据
				if(out_trade_no.contains("r")) {//不为空，说明为进行充值操作
					Integer uid = Integer.valueOf(StringUtils.substringBefore(out_trade_no, "-"));
					/*if(total_fee.equals("1")){
						total_fee="50000";
					}*/
					BigDecimal orderAmout = new BigDecimal(total_fee);
					orderAmout = orderAmout.divide(new BigDecimal("100"));
					WfRechargeEntity recharge = rechargeService.queryByValue(orderAmout.intValue());
					Integer give = recharge.getRebate().intValue();
					String userSource = "---android";
					if(out_trade_no.contains("wxr")){
						userSource = "---wxh5";
					}
					if(give != 0) {
						System.out.println("give"+give);
						WfMemberGiveCoinLogEntity memberGiveCoinLog = new WfMemberGiveCoinLogEntity();//充值赠送新铜钱
						memberGiveCoinLog.setCoinvalue(new BigDecimal(give));//赠送铜钱
						memberGiveCoinLog.setCreatetime(new Date());
						memberGiveCoinLog.setOrdercode(out_trade_no);
						memberGiveCoinLog.setSource(8);
						memberGiveCoinLog.setTouserid(0);
						memberGiveCoinLog.setStatus(2);//1，进行中； 2，完成
						memberGiveCoinLog.setType(1);//1，赚；2，花
						memberGiveCoinLog.setUserid(uid);
						memberGiveCoinLog.setRemarkinfo("充值返利");
						memberGiveCoinLogService.save(memberGiveCoinLog);
					}
					WfMemberGoldLogEntity memberGoldLog = new WfMemberGoldLogEntity();
					memberGoldLog.setCreatetime(new Date());
					memberGoldLog.setGoldvalue(orderAmout);//充值的金币
					memberGoldLog.setOrderNo(out_trade_no);
					memberGoldLog.setStatus(2);//1，进行中； 2，完成
					memberGoldLog.setType(1);//1，赚；2，花
					memberGoldLog.setUserid(uid);
					memberGoldLog.setUsersource(userSource);//用户来源（android/ios/h5）
					memberGoldLogService.save(memberGoldLog);

					if(userSource.contains("android")){
						WfNewMessageEntity newMessageEntity  = new WfNewMessageEntity(uid,null,4,0,"充值成功提醒","恭喜您已充值成功！！！",new Date(),null,null,
								"<br/>&nbsp;&nbsp;&nbsp;&nbsp;【好芳法课堂】尊敬的用户，您于"+new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date())+"成功在安卓端APP充值<strong> "+orderAmout+" </strong>铜钱，并获得了<strong> "+give.intValue()+" </strong>个赠送铜钱。<br/>&nbsp;&nbsp;&nbsp;&nbsp;请关注微信公众号：<strong>好芳法课堂</strong>，第一时间获得最新活动消息。");
						newMessageService.save(newMessageEntity);
					}else {
						WfNewMessageEntity newMessageEntity = new WfNewMessageEntity(uid, null, 4, 0, "充值成功提醒", "恭喜您已充值成功！！！", new Date(), null, null,
								"<br/>&nbsp;&nbsp;&nbsp;&nbsp;【好芳法课堂】尊敬的用户，您于" + new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date()) + "成功在微信公众号充值<strong> " + orderAmout + " </strong>铜钱，并获得了<strong> " + give.intValue() + " </strong>个赠送铜钱。<br/>&nbsp;&nbsp;&nbsp;&nbsp;请关注微信公众号：<strong>好芳法课堂</strong>，第一时间获得最新活动消息。");
						newMessageService.save(newMessageEntity);
					}
					//充值订单记录数据
					WfMemberRechargeOrderEntity memberRechargeOrder = new WfMemberRechargeOrderEntity();
					memberRechargeOrder.setUserid(uid);
					memberRechargeOrder.setRechargeMoney(orderAmout);
					memberRechargeOrder.setOrderNo(out_trade_no);
					memberRechargeOrder.setRebate(new BigDecimal(give));
					memberRechargeOrder.setTransactionId(trade_no);
					memberRechargeOrder.setOrderPaytime(new Date());
					memberRechargeOrder.setPayType(Integer.valueOf(1));//支付类型（1微信2支付宝，3苹果）
					memberRechargeOrder.setOrderStatus(3);//订单类型（1生成订单2支付中3支付成功）
					memberRechargeOrder.setOrderTime(new Date());
					memberRechargeOrder.setUpdatetime(new Date());
					memberRechargeOrder.setUsersource("8"+userSource);//用户来源（android/ios/h5）
					if(!"0".equals(give)) {
						memberRechargeOrder.setRemark("使用微信充值"+orderAmout.intValue()+"元,赠送铜钱"+give+"。");
					}else {
						memberRechargeOrder.setRemark("使用微信充值"+orderAmout.intValue()+"元");
					}
					memberRechargeOrderService.save(memberRechargeOrder);
					log.info("充值回调成功");
				}else {
					List<WfGoodsOrderRelationEntity> goodsOrderRelationList = goodsOrderRelationService.queryList(map1);
					if(goodsOrderRelationList.size()>0) {
						for(int i=0; i<goodsOrderRelationList.size(); i++) {
							WfGoodsOrderRelationEntity goodsOrderRelation = goodsOrderRelationList.get(i);
							goodsOrderRelation.setOrderstatus(4);//关联订单状态为成功
							goodsOrderRelationService.update(goodsOrderRelation);//保存
							if(1 == goodsOrderRelation.getGoodssort()) {
								WfCourseInfoEntity courseInfo = courseInfoService.queryObjectIgnoreStatus(goodsOrderRelation.getGoodsid());
								if(null == courseInfo) {
									System.out.println("关联课程为空");
								}
								int salenum = courseInfo.getCoursesalenumber() + 1;
								courseInfo.setCoursesalenumber(salenum);
								courseInfoService.update(courseInfo);
							}else if(2 == goodsOrderRelation.getGoodssort()){
								WfCourseChapterEntity courseChapter = courseChapterService.queryObjectIgnoreStatus(goodsOrderRelation.getGoodsid());
								if(null == courseChapter) {
									System.out.println("关联章节为空");
								}
								int salenum = courseChapter.getChaptersalenumber() + 1;
								courseChapter.setChaptersalenumber(salenum);
								courseChapterService.update(courseChapter);
							}else if(3 == goodsOrderRelation.getGoodssort()){
								WfVipCardEntity vipCard = vipCardService.queryObject(goodsOrderRelation.getGoodsid());
								if(null == vipCard) {
									System.out.println("关联课程包为空");
								}
								int salenum = vipCard.getCardsalenumber() + 1;
								vipCard.setCardsalenumber(salenum);
								vipCardService.update(vipCard);
							}
						}

						//订单状态
						goodsOrder.setOrderstatus(4);//改为已完成
						goodsOrder.setTransactionId(trade_no);//微信订单号
						SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
						goodsOrder.setOrderpaytime(sdf.parse(time_end));
						goodsOrderService.update(goodsOrder);

						//若有抽奖活动，则进行信息通知（抽奖码消息，抽奖码保存）
						WfMemberCouponsEntity memberCoupons = memberCouponsService.queryObject(goodsOrder.getCouponsId());//获取用户选择的优惠券
						BigDecimal cost = goodsOrder.getSpendcoin().add(goodsOrder.getOrderamount()).add(
								memberCoupons==null?BigDecimal.ZERO:new BigDecimal(memberCoupons.getCost()));
						List<WfLuckyEntity> list = luckyService.queryList(cost.intValue());
						if(list.size()>0){
							String code = "";
							if(list.get(0).getId()==1){
								code = "WA-"+ goodsOrder.getUserid() + "-"+ getStringRandom(4);
							}else if(list.get(0).getId()==2){
								code = "IP-"+ goodsOrder.getUserid() + "-"+ getStringRandom(4);
							}if(list.get(0).getId()==3){
								code = "XR-"+ goodsOrder.getUserid() + "-"+ getStringRandom(4);
							}
							WfNewMessageEntity newMessageEntity  = new WfNewMessageEntity(goodsOrder.getUserid(),null,4,0,"抽奖活动提醒","恭喜您获取了本次抽奖活动的抽奖码！！！",new Date(),null,null,
									"&nbsp;&nbsp;【好芳法课堂】尊敬的用户，因您在本平台消费满"+list.get(0).getTarget()+"元，获得奖品<strong>"+list.get(0).getGood()+"</strong>的抽奖码一个：<strong>"+code+"</strong>。活动将于"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(list.get(0).getEndtime()) +"结束，抽奖结果将于"+list.get(0).getLuckyday()+"前公布。<br/>&nbsp;&nbsp;请您保存此条信息，关注微信公众号：<strong>好芳法课堂</strong>，第一时间获得最新活动消息。");
							newMessageService.save(newMessageEntity);
							WfMemberEntity memberEntity = memberService.queryObject(goodsOrder.getUserid());
							WfLuckyCodeEntity luckyCodeEntity = new WfLuckyCodeEntity(goodsOrder.getUserid(),memberEntity.getTelephone(),new Date(),list.get(0).getId(),memberEntity.getUsername(),list.get(0).getGood(),memberEntity.getHeadimage(),cost);
							luckyCodeService.save(luckyCodeEntity);
							SendPhoneMessage.sendMes(memberEntity.getTelephone(),String.valueOf(list.get(0).getTarget()),list.get(0).getGood(),code,new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(list.get(0).getEndtime()),list.get(0).getLuckyday());
						}

						/**
						 * 分销
						 */
						Map<String, Object> map2 = new HashMap<>(), map3 = new HashMap<>(), map4 = new HashMap<>();
						map2.put("uid", goodsOrder.getUserid());
						map2.put("orderStatus", 4);
						map3.put("invitedId", goodsOrder.getUserid());
						map4.put("orderCode", goodsOrder.getOrdercode());
						Distribution distribution = distributionService.configuration();
						List<WfGoodsOrderEntity> goodsOrderList = goodsOrderService.queryList(map2);
						List<WfMemberInvitationEntity> invitationList = invitationService.queryList(map3);
						Calendar calendar = Calendar.getInstance();
						calendar.setTime(new Date());
						calendar.add(Calendar.DATE, -distribution.getNum());
						if (invitationList.size() > 0) {
							WfMemberInvitationEntity invitation = invitationList.get(0);
							if (calendar.getTime().getTime() <= invitationList.get(0).getCreatetime().getTime()) {
								goodsOrderRelationService.queryList(map4).forEach(item -> {
									if (distributionService.searchGoods(item.getGoodsid(), item.getGoodssort())) {
										BigDecimal decimal = new BigDecimal(0);
										Integer commissionRate = distributionService.searchGoodsInfo
												(item.getGoodsid(), item.getGoodssort()).getCommissionRate();
										decimal = decimal.add(item.getOldcoppercash() != null ? item.getOldcoppercash() : new BigDecimal(0))
												.add(item.getNewcoppercash() != null ? item.getNewcoppercash() : new BigDecimal(0))
												.add(item.getGold() != null ? item.getGold() : new BigDecimal(0))
												.add(item.getRealpay() != null ? item.getRealpay() : new BigDecimal(0))
												.add(item.getNewGold() != null ? item.getNewGold() : new BigDecimal(0))
												.multiply(new BigDecimal(commissionRate)).divide(new BigDecimal(100));
										WfMemberGiveCoinLogEntity reward = new WfMemberGiveCoinLogEntity();
										reward.setUserid(invitation.getInviterid());
										reward.setTouserid(goodsOrder.getUserid());
										reward.setType(1); // 1 赚 2 花
										reward.setStatus(2); // 1 审核中 2 成功
										reward.setSource(2);
										reward.setCoinvalue(decimal);
										reward.setCreatetime(new Date());
										reward.setOrdercode(goodsOrder.getOrdercode());
										reward.setRemarkinfo("邀请用户买课赠送铜钱");
										memberGiveCoinLogService.save(reward);
										Long time = System.currentTimeMillis() / 1000;
										distributionService.addRecord(new Distribution(invitation.getInviterid(), goodsOrder.getUserid(), goodsOrder.getOrdercode(), decimal.doubleValue(),
												1, time.intValue(), time.intValue(), item.getGoodsid(), item.getGoodssort(), commissionRate));
									}
								});
							} else if (goodsOrderList.size() == 1) {
								// 邀请关系过期，首单返还。
								goodsOrderRelationService.queryList(map4).forEach(item -> {
									BigDecimal decimal = new BigDecimal(0);
									Integer commissionRate = distribution.getCommissionRate();
									decimal = decimal.add(item.getOldcoppercash() != null ? item.getOldcoppercash() : new BigDecimal(0))
											.add(item.getNewcoppercash() != null ? item.getNewcoppercash() : new BigDecimal(0))
											.add(item.getGold() != null ? item.getGold() : new BigDecimal(0))
											.add(item.getRealpay() != null ? item.getRealpay() : new BigDecimal(0))
											.add(item.getNewGold() != null ? item.getNewGold() : new BigDecimal(0))
											.multiply(new BigDecimal(commissionRate)).divide(new BigDecimal(100));
									WfMemberGiveCoinLogEntity reward = new WfMemberGiveCoinLogEntity();
									reward.setUserid(invitation.getInviterid());
									reward.setTouserid(goodsOrder.getUserid());
									reward.setType(1); // 1 赚 2 花
									reward.setStatus(2); // 1 审核中 2 成功
									reward.setSource(2);
									reward.setCoinvalue(decimal);
									reward.setCreatetime(new Date());
									reward.setOrdercode(goodsOrder.getOrdercode());
									reward.setRemarkinfo("邀请用户买课首单赠送铜钱");
									memberGiveCoinLogService.save(reward);
									Long time = System.currentTimeMillis() / 1000;
									distributionService.addRecord(new Distribution(invitation.getInviterid(), goodsOrder.getUserid(), goodsOrder.getOrdercode(), decimal.doubleValue(),
											1, time.intValue(), time.intValue(), item.getGoodsid(), item.getGoodssort(), commissionRate));
								});
							}
						}

						//原铜钱余额
						WfCoinLogEntity coinLog = coinLogService.queryByOrderCode(out_trade_no);
						if(coinLog != null) {
							coinLog.setStatus(2);//成功
							coinLogService.update(coinLog);
						}
					}

					//金币
					WfMemberGoldLogEntity memberGoldLog = memberGoldLogService.queryByOrderCode(out_trade_no);
					if(memberGoldLog != null) {
						memberGoldLog.setStatus(2);//成功
						memberGoldLogService.update(memberGoldLog);
					}

					//新金币
					WfMemberNewGoldLogEntity memberNewGoldLog = memberNewGoldLogService.queryByOrderCode(out_trade_no);
					if(memberNewGoldLog != null) {
						memberNewGoldLog.setStatus(2);//成功
						memberNewGoldLogService.update(memberNewGoldLog);
					}

					//新铜钱
					map1.put("type", 2);
					List<WfMemberGiveCoinLogEntity> memberGiveCoinLogList = memberGiveCoinLogService.queryByOrderCode(map1);
					if(memberGiveCoinLogList.size()>0) {
						memberGiveCoinLogList.get(0).setStatus(2);//成功
						memberGiveCoinLogService.update(memberGiveCoinLogList.get(0));
					}
				}

				log.info("微信支付，交易成功");
				resHandler.sendToCFT("SUCCESS");
			}else {
				log.info("微信支付失败");
				resHandler.sendToCFT("FAIL");
			}

		} catch (Exception e) {
			e.printStackTrace();
			try {
				resHandler.sendToCFT("FAIL");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}

	/**
	 * 查询微信账单
	 * @throws Exception
	 */
	@RequestMapping(value = "doQuery")
	@IgnoreSign
	@IgnoreToken
	@ResponseBody
	public R doQuery(HttpServletRequest req) throws Exception {
		String orderNum = req.getParameter("orderNum");//购物订单查询
		String source = req.getParameter("source");//购物订单查询
		//String transactionId = goodsOrder.getTransactionId();
		// 商户相关资料

		Map<String,String> map = new HashMap<String,String>();
		while(!("SUCCESS".equals(map.get("trade_state")))) {
			orderNum = req.getParameter("orderNum");//购物订单查询
			source = req.getParameter("source");//购物订单查询
			WfGoodsOrderEntity goodsOrder = new WfGoodsOrderEntity();
			goodsOrder = goodsOrderService.queryByOrderCode(orderNum);

			String appid = null;
			String partner = null;
			String partnerkey = null;
			if("h5".equals(source)){
				appid = ConstantUtil.GG_APP_ID;
				partner = ConstantUtil.GG_PARTNER;
				partnerkey = ConstantUtil.GG_PARTNER_KEY;
			}else{
				appid = ConstantUtil.APP_ID;
				// String appsecret = ConstantUtil.APP_SECRET;
				partner = ConstantUtil.PARTNER;
				partnerkey = ConstantUtil.PARTNER_KEY;
			}

			WXOrderQuery query = new WXOrderQuery();
			query.setAppid(appid);//应用APPID
			query.setMch_id(partner);//商户号
			Random random = new Random();
			String randomStr = MD5Util.MD5Encode(String.valueOf(random.nextInt(1000000)), "utf-8").toUpperCase();
			System.out.println("randomStr="+randomStr);
			query.setNonce_str(MD5Util.MD5Encode(randomStr, "utf-8").toLowerCase());//随机字符串
			query.setOut_trade_no(orderNum);//商户订单号
			query.setPartnerKey(partnerkey);//API秘钥
			//query.setTransaction_id(transactionId);//微信订单号(或商户订单号 二选一)
			query.setSign(createSign(query, partnerkey));//签名

			map = query.reqOrderquery();

			if("SUCCESS".equals(map.get("trade_state"))) {

				WfBillEntity b = billService.queryByOrderNum(orderNum);
				if(null == b) {
					WfBillEntity bill = new WfBillEntity();
					bill.setTradetime(map.get("time_end"));//支付完成时间
					bill.setGhid(map.get("appid"));//app/公众号id
					bill.setMchid(map.get("mch_id"));//商户号
					bill.setSubmch("0");//子商户号
					bill.setDeviceid(map.get("device_info"));//设备号
					bill.setWxorder(map.get("transaction_id"));//微信支付订单号
					bill.setBzorder(map.get("out_trade_no"));//商户订单号
					bill.setOpenid(map.get("openid"));//用户标识
					bill.setTradetype(map.get("trade_type"));//交易类型
					bill.setTradestatus(map.get("trade_state"));//交易状态   SUCCESS—支付成功 REFUND—转入退款 NOTPAY—未支付 CLOSED—已关闭 REVOKED—已撤销（刷卡支付） USERPAYING--用户支付中 PAYERROR--支付失败(其他原因，如银行返回失败)
					bill.setBank(map.get("bank_type"));//付款银行
					bill.setCurrency(map.get("fee_type"));//货币种类
					bill.setTotalmoney(map.get("cash_fee"));//现金支付金额
					bill.setRedpacketmoney(map.get("coupon_fee"));//代金券金额
					bill.setWxrefund("0");//微信退款单号
					bill.setBzrefund("0");//商户退款单号
					bill.setRefundmoney("0.00");//退款金额
					//bill.setRefundtype((String) map.get("time_end"));//退款类型
					//bill.setRefundstatus((String) map.get("time_end"));//退款状态
					String productname = "";
					if("".equals(orderNum)) {//若购物订单号为空，则说明在操作充值
						bill.setProductname("充值");
					}else {
						Map<String,Object> map1 =new  HashMap<String,Object>();
						map1.put("orderCode", goodsOrder.getOrdercode());
						List<WfGoodsOrderRelationEntity> goodsOrderRelationList = goodsOrderRelationService.queryList(map1);
						for(int i=0; i<goodsOrderRelationList.size(); i++) {
							WfGoodsOrderRelationEntity goodsOrderRelation = goodsOrderRelationList.get(i);
							if(1 == goodsOrderRelation.getGoodssort()) {
								WfCourseInfoEntity courseInfo = courseInfoService.queryObjectIgnoreStatus(goodsOrderRelation.getGoodsid());
								productname = productname + courseInfo.getCoursename();
							}else if(2 == goodsOrderRelation.getGoodssort()){
								WfCourseChapterEntity courseChapter = courseChapterService.queryObjectIgnoreStatus(goodsOrderRelation.getGoodsid());
								productname = productname + courseChapter.getChaptername();
							}else if(3 == goodsOrderRelation.getGoodssort()){
								WfVipCardEntity vipCard = vipCardService.queryObject(goodsOrderRelation.getGoodsid());
								productname = productname + vipCard.getCardname();
							}
						}
						bill.setProductname(productname);//商品名称
					}
					bill.setBzdatapacket("");//商户数据包
					double fee = Double.valueOf((String) map.get("cash_fee"))*0.006;
					bill.setFee(String.valueOf(Math.round(fee*100000)/100000));
					bill.setRate("0.6%");

					billService.save(bill);
				}
				WfMemberCouponsEntity coupon = memberCouponsService.queryObject(goodsOrder.getCouponsId());
				Map<String,Object> resultMap =new  HashMap<String,Object>();
				resultMap.put("coinvalue", goodsOrder.getSpendcoin());
				resultMap.put("oldcoppercash", goodsOrder.getOldcoppercash());
				resultMap.put("newcoppercash", goodsOrder.getNewcoppercash());
				resultMap.put("gold", goodsOrder.getGold());
				resultMap.put("newGold", goodsOrder.getNewGold());
				resultMap.put("totalCoin", goodsOrder.getSpendcoin());
				resultMap.put("price",Double.valueOf(map.get("cash_fee")));
				if(null != coupon) {
					resultMap.put("couponsCost", coupon.getCost());
				}else {
					resultMap.put("couponsCost", 0);
				}
				resultMap.put("totalPrice", goodsOrder.getOrderamount());//总金额
				return R.ok(resultMap);
			}else if("PAYERROR".equals(map.get("trade_state"))) {
				return R.error(57, "支付失败");
			}else if("ORDERPAID".equals(map.get("trade_state")) ) {
				log.info("商户订单已支付");
				return R.error(64, "订单已支付,请联系管理员");
			}else if("SIGNERROR".equals(map.get("trade_state")) ) {
				log.info("签名错误");
				return R.error(65, "签名错误");
			}else if("NOTPAY".equals(map.get("trade_state")) ) {
				log.info("订单未支付");
				return R.error(69, "订单未支付");
			}else if("ORDERNOTEXIST".equals(map.get("err_code"))){
				log.info("此交易订单号不存在");
				return R.error(69, "此交易订单号不存在");
			}
    	/*else if("USERPAYING".equals(map.get("trade_state"))) {
    		return R.error(56, "订单支付中");
    	}*/
		}
		return R.error("交易失败，请联系管理员。");
	}

	/**
	 * 查询充值账单
	 * @throws Exception
	 */
	@RequestMapping(value = "rechargeQuery1")
	@ResponseBody
	public R rechargeQuery1(HttpServletRequest req) throws Exception {
		Integer uid = ISsoLoginHelper.confirm(req);
		String orderNum = req.getParameter("orderNum");//购物订单查询
		String payType = req.getParameter("payType");//支付类型（1微信2支付宝，3苹果）
		Double give = Double.valueOf(req.getParameter("give")) ;//赠送铜钱
		String userSource = req.getParameter("userSource");//用户来源 +（---android/---ios/---wxh5）
		String price = req.getParameter("price");
		BigDecimal orderAmout = new BigDecimal(price);//支付费用

		Map<String,String> map = new HashMap<String,String>();
		while(!("SUCCESS".equals(map.get("trade_state")))) {
			orderNum = req.getParameter("orderNum");//订单查询

			String appid = null;
			String partner = null;
			String partnerkey = null;
			if(userSource.contains("android")){
				appid = ConstantUtil.APP_ID;
				partner = ConstantUtil.PARTNER;
				partnerkey = ConstantUtil.PARTNER_KEY;
			}else{
				appid = ConstantUtil.GG_APP_ID;
				partner = ConstantUtil.GG_PARTNER;
				partnerkey = ConstantUtil.GG_PARTNER_KEY;
			}

			WXOrderQuery query = new WXOrderQuery();
			query.setAppid(appid);//应用APPID
			query.setMch_id(partner);//商户号
			Random random = new Random();
			String randomStr = MD5Util.MD5Encode(String.valueOf(random.nextInt(1000000)), "utf-8").toUpperCase();
			System.out.println("randomStr="+randomStr);
			query.setNonce_str(MD5Util.MD5Encode(randomStr, "utf-8").toLowerCase());//随机字符串
			query.setOut_trade_no(orderNum);//商户订单号
			query.setPartnerKey(partnerkey);//API秘钥
			//query.setTransaction_id(transactionId);//微信订单号(或商户订单号 二选一)
			query.setSign(createSign(query, partnerkey));//签名

			map = query.reqOrderquery();

			if("SUCCESS".equals(map.get("trade_state"))) {
	    		/*Map<String,Object> map2 =new  HashMap<String,Object>();
				map2.put("orderCode", orderNum);
	        	List<WfMemberGiveCoinLogEntity> memberGiveCoinLogList = memberGiveCoinLogService.queryByOrderCode(map2);
	        	for(int i=0; i<memberGiveCoinLogList.size(); i++) {
	        		WfMemberGiveCoinLogEntity memberGiveCoinLog = memberGiveCoinLogList.get(i);
		        	memberGiveCoinLog.setType(1);
		        	memberGiveCoinLog.setStatus(2);
		        	memberGiveCoinLogService.update(memberGiveCoinLog);
	        	}
	        	WfMemberGoldLogEntity memberGoldLog = memberGoldLogService.queryByOrderCode(orderNum);
	        	memberGoldLog.setType(1);
	        	memberGoldLog.setStatus(2);
	        	memberGoldLogService.update(memberGoldLog);

	        	Map<String,Object> map1 = new HashMap<String,Object>();
	        	map1.put("orderCode", orderNum);
	        	WfMemberRechargeOrderEntity memberRechargeOrder = memberRechargeOrderService.queryByOrderNum(map1);
	        	memberRechargeOrder.setOrderStatus(3);
	        	memberRechargeOrderService.update(memberRechargeOrder);*/

				if(give != 0) {
					System.out.println("give"+give);
					WfMemberGiveCoinLogEntity memberGiveCoinLog = new WfMemberGiveCoinLogEntity();//充值赠送新铜钱
					memberGiveCoinLog.setCoinvalue(new BigDecimal(give));//赠送铜钱
					memberGiveCoinLog.setCreatetime(new Date());
					memberGiveCoinLog.setOrdercode(orderNum);
					memberGiveCoinLog.setSource(8);
					memberGiveCoinLog.setTouserid(0);
					memberGiveCoinLog.setStatus(2);//1，进行中； 2，完成
					memberGiveCoinLog.setType(1);//1，赚；2，花
					memberGiveCoinLog.setUserid(uid);
					memberGiveCoinLog.setRemarkinfo("充值返利");
					memberGiveCoinLogService.save(memberGiveCoinLog);
				}
				WfMemberGoldLogEntity memberGoldLog = new WfMemberGoldLogEntity();
				memberGoldLog.setCreatetime(new Date());
				memberGoldLog.setGoldvalue(orderAmout);//充值的金币
				memberGoldLog.setOrderNo(orderNum);
				memberGoldLog.setStatus(2);//1，进行中； 2，完成
				memberGoldLog.setType(1);//1，赚；2，花
				memberGoldLog.setUserid(uid);
				memberGoldLog.setUsersource(userSource);//用户来源（android/ios/h5）
				memberGoldLogService.save(memberGoldLog);

				/*WfMemberNewGoldLogEntity memberNewGoldLog = new WfMemberNewGoldLogEntity();
				memberNewGoldLog.setCreatetime(new Date());
				memberNewGoldLog.setGoldvalue(orderAmout);//充值的金币
				memberNewGoldLog.setOrderNo(orderNum);
				memberNewGoldLog.setStatus(2);//1，进行中； 2，完成
				memberNewGoldLog.setType(1);//1，赚；2，花
				memberNewGoldLog.setUserid(uid);
				memberNewGoldLog.setUsersource(userSource);//用户来源（android/ios/h5）
				memberNewGoldLogService.save(memberNewGoldLog);*/
				if(userSource.contains("android")){
					WfNewMessageEntity newMessageEntity  = new WfNewMessageEntity(uid,null,4,0,"充值成功提醒","恭喜您已充值成功！！！",new Date(),null,null,
							"<br/>&nbsp;&nbsp;&nbsp;&nbsp;【好芳法课堂】尊敬的用户，您于"+new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date())+"成功在安卓端APP充值<strong> "+orderAmout+" </strong>铜钱，并获得了<strong> "+give.intValue()+" </strong>个赠送铜钱。<br/>&nbsp;&nbsp;&nbsp;&nbsp;请关注微信公众号：<strong>好芳法课堂</strong>，第一时间获得最新活动消息。");
					newMessageService.save(newMessageEntity);
				}else {
					WfNewMessageEntity newMessageEntity = new WfNewMessageEntity(uid, null, 4, 0, "充值成功提醒", "恭喜您已充值成功！！！", new Date(), null, null,
							"<br/>&nbsp;&nbsp;&nbsp;&nbsp;【好芳法课堂】尊敬的用户，您于" + new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date()) + "成功在微信公众号充值<strong> " + orderAmout + " </strong>铜钱，并获得了<strong> " + give.intValue() + " </strong>个赠送铜钱。<br/>&nbsp;&nbsp;&nbsp;&nbsp;请关注微信公众号：<strong>好芳法课堂</strong>，第一时间获得最新活动消息。");
					newMessageService.save(newMessageEntity);
				}
				//充值订单记录数据
				WfMemberRechargeOrderEntity memberRechargeOrder = new WfMemberRechargeOrderEntity();
				memberRechargeOrder.setUserid(uid);
				memberRechargeOrder.setRechargeMoney(orderAmout);
				memberRechargeOrder.setOrderNo(orderNum);
				memberRechargeOrder.setRebate(new BigDecimal(give));
				memberRechargeOrder.setTransactionId(map.get("transaction_id"));
				memberRechargeOrder.setOrderPaytime(new Date());
				memberRechargeOrder.setPayType(Integer.valueOf(payType));//支付类型（1微信2支付宝，3苹果）
				memberRechargeOrder.setOrderStatus(3);//订单类型（1生成订单2支付中3支付成功）
				memberRechargeOrder.setOrderTime(new Date());
				memberRechargeOrder.setUpdatetime(new Date());
				memberRechargeOrder.setUsersource("8"+userSource);//用户来源（android/ios/h5）
				if(!"0".equals(give)) {
					memberRechargeOrder.setRemark("使用微信充值"+price+"元,赠送铜钱"+give+"。");
				}else {
					memberRechargeOrder.setRemark("使用微信充值"+price+"元");
				}
				memberRechargeOrderService.save(memberRechargeOrder);
				return R.ok();
			}else if("PAYERROR".equals(map.get("trade_state"))) {
				return R.error(57, "支付失败");
			}else if("ORDERPAID".equals(map.get("trade_state")) ) {
				log.info("商户订单已支付");
				return R.error(64, "订单已支付,请联系管理员");
			}else if("SIGNERROR".equals(map.get("trade_state")) ) {
				log.info("签名错误");
				return R.error(65, "签名错误");
			}else if("NOTPAY".equals(map.get("trade_state")) ) {
				log.info("订单未支付");
				return R.error(69, "订单未支付");
			}
	    	/*else if("USERPAYING".equals(map.get("trade_state"))) {
	    		return R.error(56, "订单支付中");
	    	}*/
		}
		return R.error("交易失败，请联系管理员。");
	}

	/**
	 * 查询充值账单
	 * @throws Exception
	 */
	@RequestMapping(value = "rechargeQuery")
	@ResponseBody
	public R rechargeQuery(HttpServletRequest req) throws Exception {
		Integer uid = ISsoLoginHelper.confirm(req);
		String orderNum = req.getParameter("orderNum");//购物订单查询
		String payType = req.getParameter("payType");//支付类型（1微信2支付宝，3苹果）
		Double give = Double.valueOf(req.getParameter("give")) ;//赠送铜钱
		String userSource = req.getParameter("userSource");//用户来源 +（---android/---ios/---wxh5）
		String price = req.getParameter("price");
		BigDecimal orderAmout = new BigDecimal(price);//支付费用

		Map<String,String> map = new HashMap<String,String>();
		while(!("SUCCESS".equals(map.get("trade_state")))) {
			orderNum = req.getParameter("orderNum");//订单查询

			String appid = null;
			String partner = null;
			String partnerkey = null;
			if(userSource.contains("android")){
				appid = ConstantUtil.APP_ID;
				partner = ConstantUtil.PARTNER;
				partnerkey = ConstantUtil.PARTNER_KEY;
			}else{
				appid = ConstantUtil.GG_APP_ID;
				partner = ConstantUtil.GG_PARTNER;
				partnerkey = ConstantUtil.GG_PARTNER_KEY;
			}

			WXOrderQuery query = new WXOrderQuery();
			query.setAppid(appid);//应用APPID
			query.setMch_id(partner);//商户号
			Random random = new Random();
			String randomStr = MD5Util.MD5Encode(String.valueOf(random.nextInt(1000000)), "utf-8").toUpperCase();
			System.out.println("randomStr="+randomStr);
			query.setNonce_str(MD5Util.MD5Encode(randomStr, "utf-8").toLowerCase());//随机字符串
			query.setOut_trade_no(orderNum);//商户订单号
			query.setPartnerKey(partnerkey);//API秘钥
			//query.setTransaction_id(transactionId);//微信订单号(或商户订单号 二选一)
			query.setSign(createSign(query, partnerkey));//签名

			map = query.reqOrderquery();

			if("SUCCESS".equals(map.get("trade_state"))) {
				return R.ok();
			}else if("PAYERROR".equals(map.get("trade_state"))) {
				return R.error(57, "支付失败");
			}else if("ORDERPAID".equals(map.get("trade_state")) ) {
				log.info("商户订单已支付");
				return R.error(64, "订单已支付,请联系管理员");
			}else if("SIGNERROR".equals(map.get("trade_state")) ) {
				log.info("签名错误");
				return R.error(65, "签名错误");
			}else if("NOTPAY".equals(map.get("trade_state")) ) {
				log.info("订单未支付");
				return R.error(69, "订单未支付");
			}
	    	/*else if("USERPAYING".equals(map.get("trade_state"))) {
	    		return R.error(56, "订单支付中");
	    	}*/
		}
		return R.error("交易失败，请联系管理员。");
	}

	/**
	 * 创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
	 */
	public static String createSign(WXOrderQuery query, String AppKey) {
		SortedMap<String, String> nativeObj = new TreeMap<String, String>();
		nativeObj.put("appid", query.getAppid());
		nativeObj.put("mch_id", query.getMch_id());
		nativeObj.put("nonce_str", query.getNonce_str());
		nativeObj.put("out_trade_no", query.getOut_trade_no());
		//nativeObj.put("transaction_id", query.getTransaction_id());
		StringBuffer sb = new StringBuffer();
		Set es = nativeObj.entrySet();
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
				sb.append(k + "=" + v + "&");
			}
		}
		sb.append("key=" + AppKey);
		System.out.println("sb="+sb.toString());
		String sign = MD5Util.MD5Encode(sb.toString(), "UTF-8").toUpperCase();
		return sign;
	}

	/**
	 * 我的订单
	 */
	@RequestMapping("/myOrder")
	@ResponseBody
	public R myOrder(HttpServletRequest req) {

		Integer uid = ISsoLoginHelper.confirm(req);
		String orderStatus = req.getParameter("orderStatus");
		Map<String,Object> map =new  HashMap<String,Object>();
		map.put("uid", uid);
		if( orderStatus.length() != 0) {
			map.put("orderStatus", orderStatus);//订单状态（1.待付款2.待收货3.待评价4.已完成5.取消订单）
		}
		List<WfGoodsOrderEntity>  goodsOrderList = goodsOrderService.queryMyOrder(map);//根据uid获取订单
		//判断待付款订单是否已超时可支付时间，若超时则默认取消订单 （支付时间：一个小时）
		if(null != goodsOrderList) {
			for(int i=0; i<goodsOrderList.size(); i++) {
				WfGoodsOrderEntity goodsOrder = goodsOrderList.get(i);
				if(goodsOrder.getOrderstatus() == 1) {
					Date orderDate = goodsOrder.getOrdertime();
					int result = timeComp(orderDate);
					if(result==-1) {
						WfGoodsOrderEntity order = goodsOrderService.queryObject(goodsOrder.getId());
						order.setOrderstatus(5);
						goodsOrderService.update(order);
						goodsOrderList = goodsOrderService.queryMyOrder(map);//更新查询结果

						map.put("orderCode", goodsOrder.getOrdercode());
						List<WfGoodsOrderRelationEntity> goodsOrderRelationList = goodsOrderRelationService.queryList(map);
						if(goodsOrderRelationList.size()>0) {
							for(int m=0; m<goodsOrderRelationList.size(); m++) {
								WfGoodsOrderRelationEntity goodsOrderRelation = goodsOrderRelationList.get(m);
								goodsOrderRelation.setOrderstatus(5);//关联订单状态为取消订单
								goodsOrderRelationService.update(goodsOrderRelation);//保存
							}
						}

						if(null != order.getCouponsId() && 0!= order.getCouponsId()  ) {
							WfMemberCouponsEntity coupon = memberCouponsService.queryObject(order.getCouponsId());
							coupon.setStatus(2);//将状态改为未使用
							memberCouponsService.update(coupon);//解锁优惠券
						}
						//原铜钱余额
						if(null != order.getOrdercode()) {
							WfCoinLogEntity coinLog = coinLogService.queryByOrderCode(order.getOrdercode());
							if(coinLog != null) {
								coinLogService.delete(coinLog.getId());//解锁
							}

							//新铜钱
							Map<String,Object> map1 =new  HashMap<String,Object>();
							map1.put("orderCode", goodsOrder.getOrdercode());
							map1.put("type", 2);
							List<WfMemberGiveCoinLogEntity> memberGiveCoinLogList = memberGiveCoinLogService.queryByOrderCode(map1);
							if(memberGiveCoinLogList.size()>0) {
								memberGiveCoinLogService.delete(memberGiveCoinLogList.get(0).getId());//解锁
							}

							//金币
							WfMemberGoldLogEntity memberGoldLog = memberGoldLogService.queryByOrderCode(order.getOrdercode());
							if(memberGoldLog != null) {
								memberGoldLogService.delete(memberGoldLog.getId());//解锁
							}

							//新金币
							WfMemberNewGoldLogEntity memberNewGoldLog = memberNewGoldLogService.queryByOrderCode(order.getOrdercode());
							if(memberNewGoldLog != null) {
								memberNewGoldLogService.delete(memberNewGoldLog.getId());//解锁
							}
						}
					}
				}
			}
			for(int i=0; i<goodsOrderList.size(); i++) {
				List<WfGoodsOrderRelationEntity>  goodsOrderRelationList = goodsOrderList.get(i).getGoodsOrderRelationList();
				for(int j=0; j<goodsOrderRelationList.size(); j++) {
					WfGoodsOrderRelationEntity goodsOrderRelation = goodsOrderRelationList.get(j);
					int goodsSort = goodsOrderRelation.getGoodssort();//商品分类（1.课程 2.章节3.vip卡4商品）
					int goodsId = goodsOrderRelation.getGoodsid();
					if(goodsSort == 1) {
						WfCourseInfoEntity  courseInfoEntity =  courseInfoService.querySimpleObject(goodsId);
						if(null != courseInfoEntity) {
							courseInfoEntity.setActivityprice(goodsOrderRelation.getGoodsprice().toString());
							goodsOrderRelation.setCourseInfoEntity(courseInfoEntity);
						}
					}else if(goodsSort == 2) {
						WfCourseChapterEntity  courseChapterEntity = courseChapterService.querySimpleObject(goodsId);
						if(null != courseChapterEntity) {
							courseChapterEntity.setChapterprice(goodsOrderRelation.getGoodsprice().toString());
							goodsOrderRelation.setCourseChapterEntity(courseChapterEntity);
						}
					}else if(goodsSort == 3) {
						WfVipCardEntity  vipCardEntity = vipCardService.querySimpleObject(goodsId);
						if(null != vipCardEntity) {
							vipCardEntity.setCardprice(goodsOrderRelation.getGoodsprice().toString());
							goodsOrderRelation.setVipCardEntity(vipCardEntity);
						}
					}
				}
			}
		}

		return R.ok().put("goodsOrderList", goodsOrderList);
	}

	/**
	 * 取消订单
	 */
	@RequestMapping("/cancelOrder")
	@ResponseBody
	public R cancelOrder(HttpServletRequest req) {

		Integer uid = ISsoLoginHelper.confirm(req);
		String orderNum = req.getParameter("orderNum");
		Map<String,Object> map =new  HashMap<String,Object>();
		//订单状态（1.待付款2.待收货3.待评价4.已完成5.取消订单）
		WfGoodsOrderEntity  goodsOrder = goodsOrderService.queryByOrderCode(orderNum);//根据uid获取订单
		goodsOrder.setOrderstatus(5);
		goodsOrderService.update(goodsOrder);

		map.put("orderCode", orderNum);
		List<WfGoodsOrderRelationEntity> goodsOrderRelationList = goodsOrderRelationService.queryList(map);
		if(goodsOrderRelationList.size()>0) {
			for(int i=0; i<goodsOrderRelationList.size(); i++) {
				WfGoodsOrderRelationEntity goodsOrderRelation = goodsOrderRelationList.get(i);
				goodsOrderRelation.setOrderstatus(5);//关联订单状态为取消订单
				goodsOrderRelationService.update(goodsOrderRelation);//保存
			}
		}
		//原铜钱， 新铜钱，金币
		if(null != goodsOrder.getCouponsId() && 0 != goodsOrder.getCouponsId() ) {
			WfMemberCouponsEntity coupon = memberCouponsService.queryObject(goodsOrder.getCouponsId());
			coupon.setStatus(2);//将状态改为未使用
			memberCouponsService.update(coupon);//解锁优惠券
		}
		//原铜钱余额
		if(null != goodsOrder.getOrdercode()) {
			WfCoinLogEntity coinLog = coinLogService.queryByOrderCode(goodsOrder.getOrdercode());
			if(coinLog != null) {
				coinLogService.delete(coinLog.getId());//解锁
			}

			//新铜钱
			Map<String,Object> map1 =new  HashMap<String,Object>();
			map1.put("orderCode", goodsOrder.getOrdercode());
			map1.put("type", 2);
			List<WfMemberGiveCoinLogEntity> memberGiveCoinLogList = memberGiveCoinLogService.queryByOrderCode(map1);
			if(memberGiveCoinLogList.size()>0) {
				memberGiveCoinLogService.delete(memberGiveCoinLogList.get(0).getId());//解锁
			}

			//金币
			WfMemberGoldLogEntity memberGoldLog = memberGoldLogService.queryByOrderCode(goodsOrder.getOrdercode());
			if(memberGoldLog != null) {
				memberGoldLogService.delete(memberGoldLog.getId());//解锁
			}

			//新金币
			WfMemberNewGoldLogEntity memberNewGoldLog = memberNewGoldLogService.queryByOrderCode(goodsOrder.getOrdercode());
			if(memberNewGoldLog != null) {
				memberNewGoldLogService.delete(memberNewGoldLog.getId());//解锁
			}
		}

		return R.ok();
	}

	public static int timeComp(Date  orderTime )  {
		long curren = System.currentTimeMillis();
		curren -= 60 * 60 * 1000;//系统当前时间减一个小时
		Date date = new Date(curren);
		int i = orderTime.compareTo(date);

		return i;
	}

	/**
	 * 已购课程
	 */
	@RequestMapping("/myCourse")
	@ResponseBody
	public R myCourse(HttpServletRequest req) {

		Map<String,Object> map =new  HashMap<String,Object>();
		Integer uid = ISsoLoginHelper.confirm(req);
		map.put("uid", uid);
		map.put("orderStatus", 4);//订单状态（1.待付款2.待收货3.待评价4.已完成5.取消订单）
		//获取已购课程个数
		List<WfGoodsOrderEntity>  goodsOrderList = goodsOrderService.queryList(map);//根据uid获取订单
		List<WfCourseInfoEntity> courseInfoList = new ArrayList<WfCourseInfoEntity>();//课程
		List<WfVipCardEntity> vipCardList = new ArrayList<WfVipCardEntity>();//课程包
		for(int i=0 ; i<goodsOrderList.size(); i++) {
			WfGoodsOrderEntity goodsOrderEntity = goodsOrderList.get(i);
			map.put("orderCode",goodsOrderEntity.getOrdercode());
			List<WfGoodsOrderRelationEntity> courseList =  goodsOrderRelationService.queryList(map);//根据订单号获取其中所有课程
			for(int j=0 ; j<courseList.size(); j++) {
				WfGoodsOrderRelationEntity gor = courseList.get(j);
				//1.课程 2.章节3.vip卡 4商品
				if(1 == gor.getGoodssort()) {
					WfCourseInfoEntity  courseInfoEntity = courseInfoService.querySimpleObject(gor.getGoodsid());
					//将订单时间存入课程时间，实现置顶功能
					courseInfoEntity.setCreatetime(gor.getCreatetime());

					if(null != courseInfoEntity) {
						courseInfoList.add(courseInfoEntity);
					}
				}else if(2 == gor.getGoodssort()){
					WfCourseChapterEntity  courseChapterEntity = courseChapterService.querySimpleObject(gor.getGoodsid());
					WfCourseInfoEntity  courseInfoEntity = courseInfoService.querySimpleObject(courseChapterEntity.getCourseid());
					//将订单时间存入课程时间，实现置顶功能
					courseInfoEntity.setCreatetime(gor.getCreatetime());

					Map<String,Object> map1 =new  HashMap<String,Object>();
					map1.put("courseId", courseInfoEntity.getId());
					map1.put("chapterType", 1);//免费
					List<WfCourseChapterEntity>  courseChapterFreeList = courseChapterService.queryFreeObject(map1);
					if(null == courseChapterFreeList) {
						courseChapterFreeList = new ArrayList<WfCourseChapterEntity>();
					}
					courseChapterFreeList.add(courseChapterEntity);
					courseInfoEntity.setCourseChapterList(courseChapterFreeList);
					if(null != courseInfoEntity) {
						courseInfoList.add(courseInfoEntity);
					}
				}else  if(3 == gor.getGoodssort()){
					WfVipCardEntity  vipCardEntity = vipCardService.querySimpleObject(gor.getGoodsid());
					//将订单时间存入课程时间，实现置顶功能
					String gorTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(gor.getCreatetime());
					vipCardEntity.setCreatetime(gorTime);

					vipCardList.add(vipCardEntity);
				}
			}
		}
		Map<String,Object> resultMap =new  HashMap<String,Object>();
		resultMap.put("courseInfoList", courseInfoList);
		resultMap.put("vipCardList", vipCardList);

		return R.ok(resultMap);
	}

	/**
	 * 判断是否是已购课程
	 */
	@RequestMapping("/isMyCourse")
	@ResponseBody
	public R isMyCourse(HttpServletRequest req,String goodSort,String goodId) {

		Map<String,Object> map =new  HashMap();
		Integer uid = ISsoLoginHelper.confirm(req);
		map.put("uid", uid);
		map.put("orderStatus", 4);//订单状态（1.待付款2.待收货3.待评价4.已完成5.取消订单）
		map.put("goodsSort", goodSort);
		map.put("goodsId", goodId);
		//获取已购课程个数
		Integer flag = goodsOrderRelationService.queryGoodOrNot(map);//判断某课程是否已购买
		return R.ok().put("flag",flag);
	}

	/**
	 * 领取免费课程
	 */
	@RequestMapping("/getActivityFreeCourse")
	@ResponseBody
	public R getActivityFreeCourse(HttpServletRequest req) {

		Map<String,Object> map =new  HashMap();
		Integer uid = ISsoLoginHelper.confirm(req);
		map.put("uid", uid);

		//判断是否已领取
		boolean flag  = true;
        if(flag) {
			String orderNum = DateUtil.getOrderCode();//根据当前时间生成订单号，yyMMddHHmmssSSS + 6位随机数
			goodsOrderService.save(WfGoodsOrderEntity.generateFreeEntity(null, orderNum));
			goodsOrderRelationService.save(WfGoodsOrderRelationEntity.generateFreeEntity
					(null, orderNum, 1, 1));
		}
		return R.ok();
	}


	/**
	 * 正在用：已购课程
	 */
	@RequestMapping("/myCourseList")
	@ResponseBody
	public R myCourseList(HttpServletRequest req) {

		Map<String,Object> map =new  HashMap<String,Object>();
		Integer uid = ISsoLoginHelper.confirm(req);
		String type = req.getParameter("type");//1、课程 ；3、课程包
		map.put("uid", uid);
		map.put("orderStatus", 4);//订单状态（1.待付款2.待收货3.待评价4.已完成5.取消订单）
		//获取已购课程个数
		List<WfGoodsOrderEntity>  goodsOrderList = goodsOrderService.queryList(map);//根据uid获取订单
		List<WfCourseInfoEntity> courseInfoList = new ArrayList<WfCourseInfoEntity>();//课程
		List<WfVipCardEntity> vipCardList = new ArrayList<WfVipCardEntity>();//课程包
		for(int i=0 ; i<goodsOrderList.size(); i++) {
			WfGoodsOrderEntity goodsOrderEntity = goodsOrderList.get(i);
			map.put("orderCode",goodsOrderEntity.getOrdercode());
			List<WfGoodsOrderRelationEntity> courseList =  goodsOrderRelationService.queryList(map);//根据订单号获取其中所有课程
			if("1".equals(type)) {
				for(int j=0 ; j<courseList.size(); j++) {
					WfGoodsOrderRelationEntity gor = courseList.get(j);
					//1.课程 2.章节3.vip卡 4商品
					if(1 == gor.getGoodssort()) {
						WfCourseInfoEntity  courseInfoEntity = courseInfoService.querySimpleObject(gor.getGoodsid());
						if(null != courseInfoEntity) {
							courseInfoList.add(courseInfoEntity);
						}
					}else if(2 == gor.getGoodssort()){
						WfCourseChapterEntity  courseChapterEntity = courseChapterService.querySimpleObject(gor.getGoodsid());
						WfCourseInfoEntity  courseInfoEntity = courseInfoService.querySimpleObject(courseChapterEntity.getCourseid());
						Map<String,Object> map1 =new  HashMap<String,Object>();
						map1.put("courseId", courseInfoEntity.getId());
						map1.put("chapterType", 1);//免费
						List<WfCourseChapterEntity>  courseChapterFreeList = courseChapterService.queryFreeObject(map1);
						if(null == courseChapterFreeList) {
							courseChapterFreeList = new ArrayList<WfCourseChapterEntity>();
						}
						courseChapterFreeList.add(courseChapterEntity);
						courseInfoEntity.setCourseChapterList(courseChapterFreeList);
						if(null != courseInfoEntity) {
							courseInfoList.add(courseInfoEntity);
						}
					}
				}
			}else if("3".equals(type)) {
				for(int j=0 ; j<courseList.size(); j++) {
					WfGoodsOrderRelationEntity gor = courseList.get(j);
					//1.课程 2.章节3.vip卡 4商品
					if(3 == gor.getGoodssort()){
						WfVipCardEntity  vipCardEntity = vipCardService.querySimpleObject(gor.getGoodsid());
						vipCardList.add(vipCardEntity);
					}
				}
			}
		}
		Map<String,Object> resultMap =new  HashMap<String,Object>();
		resultMap.put("courseInfoList", courseInfoList);
		resultMap.put("vipCardList", vipCardList);

		return R.ok(resultMap);
	}
	/**
	 * 课程包中课程
	 */
	@RequestMapping("/vipCard")
	@ResponseBody
	@IgnoreToken
	public R vipCard(HttpServletRequest req) {

		Map<String,Object> map =new  HashMap<String,Object>();
		String vipCardId = req.getParameter("vipCardId");
		map.put("vipCardId", vipCardId);

		//查询课程包中课程
		List<WfVipCardEntity> courseList = vipCardService.queryCourseList(map);

		Map<String,Object> resultMap =new  HashMap<String,Object>();
		resultMap.put("courseList", courseList);

		return R.ok(resultMap);
	}

	/**
	 * 课程中章节简要
	 */
	@RequestMapping("/courseChapter")
	@ResponseBody
	@IgnoreToken
	public R courseChapter(HttpServletRequest req) {

		Map<String,Object> map1 =new  HashMap<String,Object>();
		String courseId = req.getParameter("courseId");
		map1.put("courseId", courseId);
		map1.put("buy", courseId);
		//查询课程包中课程 querySimpleChapter
		List<WfCourseChapterEntity> myCourseChapterList= courseChapterService.querySimpleChapter(map1);
		Map<String,Object> resultMap =new  HashMap<String,Object>();
		resultMap.put("courseChapterList", myCourseChapterList);

		return R.ok(resultMap);
	}

	/**
	 * 课程中章节简要
	 */
	@RequestMapping("/freeCourseChapter")
	@ResponseBody
	public R freeCreeChapter(HttpServletRequest req) {

		Map<String,Object> map1 =new  HashMap<String,Object>();
		String courseId = req.getParameter("courseId");
		map1.put("courseId", courseId);
		//查询课程包中课程 querySimpleChapter
		List<WfCourseChapterEntity> myCourseChapterList= courseChapterService.querySimpleChapter(map1);

		List<WfCourseChapterEntity> courseChapterList = new ArrayList<WfCourseChapterEntity>();//仅展示课程中已买的章节
		List<WfGoodsOrderRelationEntity> chapterList = new ArrayList<WfGoodsOrderRelationEntity>();//所有的已买章节

		int access = -1;//标识
		Integer uid = ISsoLoginHelper.confirm(req);
		//获取已购课程个数
		map1.put("uid", uid);
		map1.put("orderStatus", 4);//订单状态（1.待付款2.待收货3.待评价4.已完成5.取消订单）
		List<WfGoodsOrderEntity>  goodsOrderList = goodsOrderService.queryList(map1);//根据uid获取订单
		for(int i=0 ; i<goodsOrderList.size(); i++) {
			int cId = Integer.parseInt(courseId);//页面传来的课程参数值
			WfGoodsOrderEntity goodsOrderEntity = goodsOrderList.get(i);
			Map<String,Object> map2 =new  HashMap<String,Object>();
			map2.put("orderCode",goodsOrderEntity.getOrdercode());
			map2.put("goodsSort",1);//1.课程 2.章节3.vip卡 4商品
			List<WfGoodsOrderRelationEntity> courseList =  goodsOrderRelationService.queryList(map2);//根据订单号获取其中的课程
			for(int j=0 ; j<courseList.size(); j++) {
				if(cId == courseList.get(j).getGoodsid()) {
					access = 1;
					break;//跳出课程循环
				}
			}
			if(access == 1) {
				break;//跳出订单循环
			}
			map2.put("goodsSort",3);//1.课程 2.章节3.vip卡 4商品
			List<WfGoodsOrderRelationEntity> vipList =  goodsOrderRelationService.queryList(map2);//根据订单号获取其中的课程包
			for(int m=0 ; m<vipList.size(); m++) {
				Integer vcId = vipList.get(m).getGoodsid();
				Map<String,Object> map3 =new  HashMap<String,Object>();
				map3.put("vipCardId",vcId);
				List<WfVipCardEntity> vipCardList = vipCardService.queryCourseList(map3);//获取课程包中个课程
				for(int k=0; k<vipCardList.size(); k++) {
					if(cId == vipCardList.get(k).getCardCourseRelationList().get(0).getCourseInfoEntity().getId()) {
						access = 1;
						break;//若课程已买，则跳出课程包循环
					}
				}
			}
			if(access == 1) {
				break;//跳出订单循环
			}
			map2.put("goodsSort",2);//1.课程 2.章节3.vip卡 4商品
			List<WfGoodsOrderRelationEntity> chapterList1 =  goodsOrderRelationService.queryList(map2);//根据订单号获取其中的章节
			for(int j=0 ; j<chapterList1.size(); j++) {
				chapterList.add(chapterList1.get(j));
			}
		}
		//判断课程中的章节是否购买
		if(access != 1) {//若未买过此课程，则判断已买的章节
			for(int n=0 ; n<chapterList.size(); n++) {
				WfGoodsOrderRelationEntity gor = chapterList.get(n);
				int flag = -1;//标识
				for(int k=0; k<myCourseChapterList.size(); k++) {
					int id = myCourseChapterList.get(k).getId();
					int goodsid = gor.getGoodsid();
					if( id == goodsid) {
						flag = k;
						break;
					}
				}
				if(flag != -1) {//若已购买则保留
					courseChapterList.add(myCourseChapterList.get(flag));
				}
			}
		}

		Map<String,Object> map3 =new  HashMap<String,Object>();
		map3.put("courseId", courseId);
		map3.put("chapterType", 1);//免费
		List<WfCourseChapterEntity>  courseChapterFreeList = courseChapterService.queryFreeObject(map3);

		Map<String,Object> resultMap =new  HashMap<String,Object>();
		if(access == 1) {
			/*for(int i=0; i<courseChapterFreeList.size(); i++) {
				myCourseChapterList.add(courseChapterFreeList.get(i));
			}*/
			resultMap.put("courseChapterList", myCourseChapterList);
		}else {
			for(int i=0; i<courseChapterFreeList.size(); i++) {
				courseChapterList.add(courseChapterFreeList.get(i));
			}
			resultMap.put("courseChapterList", courseChapterList);
		}
		return R.ok(resultMap);
	}

	/**
	 * 充值卡
	 */
	@RequestMapping("/getRecharge")
	@ResponseBody
	@IgnoreToken
	public R getRecharge(HttpServletRequest req) {

		List<WfRechargeEntity> rechargeList = rechargeService.queryList(null);
		Distribution d = distributionService.queryDistributionByKey("recharge_flag");
		R r = R.ok();
		r.put("rechargeFlag",d.getValue());
		r.put("rechargeList", rechargeList);
		return r;
	}

	//课程查重
	public int checkCourse(int uid, int courseId) {
		int access = -1;//标识
		//获取已购课程个数
		Map<String,Object> map =new  HashMap<String,Object>();
		map.put("uid", uid);
		map.put("orderStatus", 4);//订单状态（1.待付款2.待收货3.待评价4.已完成5.取消订单）
		List<WfGoodsOrderEntity>  goodsOrderList = goodsOrderService.queryList(map);//根据uid获取订单
		for(int i=0 ; i<goodsOrderList.size(); i++) {
			WfGoodsOrderEntity goodsOrderEntity = goodsOrderList.get(i);
			Map<String,Object> map2 =new  HashMap<String,Object>();
			map2.put("orderCode",goodsOrderEntity.getOrdercode());
			map2.put("goodsSort",1);//1.课程 2.章节3.vip卡 4商品
			List<WfGoodsOrderRelationEntity> courseList =  goodsOrderRelationService.queryList(map2);//根据订单号获取其中的课程
			for(int j=0 ; j<courseList.size(); j++) {
				if(courseId == courseList.get(j).getGoodsid()) {
					access = 1;
					break;//跳出课程循环
				}
			}
			if(access == 1) {
				break;//跳出订单循环
			}
			map2.put("goodsSort",3);//1.课程 2.章节3.vip卡 4商品
			List<WfGoodsOrderRelationEntity> vipList =  goodsOrderRelationService.queryList(map2);//根据订单号获取其中的课程包
			for(int m=0 ; m<vipList.size(); m++) {
				Integer vcId = vipList.get(m).getGoodsid();
				Map<String,Object> map3 =new  HashMap<String,Object>();
				map3.put("vipCardId",vcId);
				List<WfVipCardEntity> vipCardList = vipCardService.queryCourseList(map3);//获取课程包中个课程
				for(int k=0; k<vipCardList.size(); k++) {
					if(courseId == vipCardList.get(k).getCardCourseRelationList().get(0).getCourseInfoEntity().getId()) {
						access = 1;
						break;//若课程已买，则跳出课程包循环
					}
				}
			}
			if(access == 1) {
				break;//跳出订单循环
			}
		}
		return access;//若access为-1,则说明此课程没买过；为1，则说明课程已买过
	}

	//章节查重
	public  int checkChapter(int uid, int chapterId) {

		WfCourseChapterEntity courseChapter =  courseChapterService.queryObjectIgnoreStatus(chapterId);//获取当前课程
		int courseId = courseChapter.getCourseid();//章节所属的课程ID

		int access = -1;//标识
		//获取已购课程个数
		Map<String,Object> map1 =new  HashMap<String,Object>();
		map1.put("uid", uid);
		map1.put("orderStatus", 4);//订单状态（1.待付款2.待收货3.待评价4.已完成5.取消订单）
		List<WfGoodsOrderEntity>  goodsOrderList = goodsOrderService.queryList(map1);//根据uid获取订单
		for(int i=0 ; i<goodsOrderList.size(); i++) {
			WfGoodsOrderEntity goodsOrderEntity = goodsOrderList.get(i);
			Map<String,Object> map2 =new  HashMap<String,Object>();
			map2.put("orderCode",goodsOrderEntity.getOrdercode());
			map2.put("goodsSort",1);//1.课程 2.章节3.vip卡 4商品
			List<WfGoodsOrderRelationEntity> courseList =  goodsOrderRelationService.queryList(map2);//根据订单号获取其中的课程
			for(int j=0 ; j<courseList.size(); j++) {
				if(courseId == courseList.get(j).getGoodsid()) {
					access = 1;
					break;//跳出课程循环
				}
			}
			if(access == 1) {
				break;//跳出订单循环
			}
			map2.put("goodsSort",3);//1.课程 2.章节3.vip卡 4商品
			List<WfGoodsOrderRelationEntity> vipList =  goodsOrderRelationService.queryList(map2);//根据订单号获取其中的课程包
			for(int m=0 ; m<vipList.size(); m++) {
				Integer vcId = vipList.get(m).getGoodsid();
				Map<String,Object> map3 =new  HashMap<String,Object>();
				map3.put("vipCardId",vcId);
				List<WfVipCardEntity> vipCardList = vipCardService.queryCourseList(map3);//获取课程包中个课程
				for(int k=0; k<vipCardList.size(); k++) {
					if(courseId == vipCardList.get(k).getCardCourseRelationList().get(0).getCourseInfoEntity().getId()) {
						access = 1;
						break;//若课程已买，则跳出课程包循环
					}
				}
			}
			if(access == 1) {
				break;//跳出订单循环
			}
			map2.put("goodsSort",2);//1.课程 2.章节3.vip卡 4商品
			List<WfGoodsOrderRelationEntity> chapterList1 =  goodsOrderRelationService.queryList(map2);//根据订单号获取其中的章节
			for(int j=0 ; j<chapterList1.size(); j++) {
				if(chapterId == chapterList1.get(j).getGoodsid()) {
					access = 1;
				}
			}
		}
		return access;
	}

	//课程包查重
	public int checkVipCard(int uid, int vipCardId) {
		int access = -1;//标识
		//获取已购课程个数
		Map<String,Object> map1 =new  HashMap<String,Object>();
		map1.put("uid", uid);
		map1.put("orderStatus", 4);//订单状态（1.待付款2.待收货3.待评价4.已完成5.取消订单）
		List<WfGoodsOrderEntity>  goodsOrderList = goodsOrderService.queryList(map1);//根据uid获取订单
		for(int i=0 ; i<goodsOrderList.size(); i++) {
			WfGoodsOrderEntity goodsOrderEntity = goodsOrderList.get(i);
			Map<String,Object> map2 =new  HashMap<String,Object>();
			map2.put("orderCode",goodsOrderEntity.getOrdercode());
			map2.put("goodsSort",3);//1.课程 2.章节3.vip卡 4商品
			map2.put("vipCardId",vipCardId);//
			List<WfGoodsOrderRelationEntity> vipList =  goodsOrderRelationService.queryList(map2);//根据订单号获取其中的课程包
			if(vipList.size()>1) {
				access = 1;
				break;//若课程包已买，则跳出课程包循环
			}
		}
		return access;
	}


	//当前商品费用查询
	public BigDecimal getPrice(List<String>  typeList, List<String> foreignIdList, int a) {
		//所有课程原价
		double activityprice = 0.0;
		//商品类型（1.课程 2.章节3.vip卡4商品）
		if("1".equals(typeList.get(a))) {
			WfCourseInfoEntity courseInfo = courseInfoService.queryObjectIgnoreStatus(Integer.valueOf(foreignIdList.get(a)));
			activityprice = Double.valueOf(courseInfo.getActivityprice());
		}else if("2".equals(typeList.get(a))){
			WfCourseChapterEntity courseChapter = courseChapterService.queryObjectIgnoreStatus(Integer.valueOf(foreignIdList.get(a)));
			activityprice = Double.valueOf(courseChapter.getChapterprice());
		}else if("3".equals(typeList.get(a))){
			WfVipCardEntity vipCard = vipCardService.queryObject(Integer.valueOf(foreignIdList.get(a)));
			activityprice = Double.valueOf(vipCard.getCardprice());
		}
		return  BigDecimal.valueOf(activityprice);
	}

	//支付时价格计算，获取课程所占的比分
	public double[] getEveryPercent(List<String> typeList, List<String> foreignIdList,WfMemberCouponsEntity memberCoupons,BigDecimal[] couponsArr) {

		//统计所有课程原价的总价
		Double orgPrice = 0.0;
		//int send = -1;//是否有赠送课标识
		double[] p = new double[typeList.size()];//价格数组
		for(int j=0; j<typeList.size(); j++) {
			//商品类型（1.课程 2.章节3.vip卡4商品）
			if("1".equals(typeList.get(j))) {
				WfCourseInfoEntity courseInfo = courseInfoService.queryObjectIgnoreStatus(Integer.valueOf(foreignIdList.get(j)));
				double activityprice = Double.valueOf(courseInfo.getActivityprice());
				if(null!=memberCoupons && memberCoupons.getLimits()==2 && memberCoupons.getValueIds().contains(foreignIdList.get(j))){//若有指定优惠券则按比例减去优惠券金额
					activityprice = activityprice - couponsArr[j].doubleValue();
				}
				p[j] = activityprice;
				orgPrice = orgPrice + activityprice;
			}else if("2".equals(typeList.get(j))){
				WfCourseChapterEntity courseChapter = courseChapterService.queryObjectIgnoreStatus(Integer.valueOf(foreignIdList.get(j)));
				double activityprice = Double.valueOf(courseChapter.getChapterprice());
				if(null!=memberCoupons && memberCoupons.getLimits()==2 && memberCoupons.getValueIds().contains(foreignIdList.get(j))){
					activityprice = activityprice - couponsArr[j].doubleValue();
				}
				p[j] = activityprice;
				orgPrice = orgPrice + activityprice;
			}else if("3".equals(typeList.get(j))){
				WfVipCardEntity vipCard = vipCardService.queryObject(Integer.valueOf(foreignIdList.get(j)));
				double activityprice = Double.valueOf(vipCard.getCardprice());
				if(null!=memberCoupons && memberCoupons.getLimits()==2 && memberCoupons.getValueIds().contains(foreignIdList.get(j))){
					activityprice = activityprice - couponsArr[j].doubleValue();
				}
				p[j] = activityprice;
				orgPrice = orgPrice + activityprice;
			}else if( typeList.get(j).contains("[5]")){//赠送课程type为5  所有费用为0
				p[j] = 0;
				//send = 1;
			}
		}
		double[] percentArr = new double[typeList.size()];//比例数组

		//获取单个课程实际支付费用（按比例），保留两位小数
		double elsePercent = 0.0; //除了最后一个的其它比例之和
		for(int i=0; i<typeList.size(); i++) {
			Double percent = 0.00;
			percent = p[i] / orgPrice;
			percent = BigDecimal.valueOf((double) Math.round(percent * 100000000) / 100000000).setScale(8, BigDecimal.ROUND_HALF_UP).doubleValue();
			percentArr[i] = percent;
		}
		/*if(send!=1){
			for(int i=0; i<typeList.size(); i++) {
				Double percent = 0.00;
				if (i < typeList.size() - 1) {
					percent = p[i] / orgPrice;
					percent = BigDecimal.valueOf((double) Math.round(percent * 100000000) / 100000000).setScale(8, BigDecimal.ROUND_HALF_UP).doubleValue();
				}else{
					percent = 1 - elsePercent;
				}
				percentArr[i] = percent;
			}
		}else{
			for(int i=0; i<typeList.size(); i++) {
				Double percent = 0.00;
				if (i < typeList.size() - 1) {
					percent = p[i] / orgPrice;
					percent = BigDecimal.valueOf((double) Math.round(percent * 100000000) / 100000000).setScale(8, BigDecimal.ROUND_HALF_UP).doubleValue();
				}
				percentArr[i] = percent;
			}
		}*/

		return  percentArr;
	}

	//指定优惠券按比例扣除
	public BigDecimal[] getLimitCouponsPrice(List<String> typeList, List<String> foreignIdList, WfMemberCouponsEntity memberCoupons) {
		//统计所有课程原价的总价
		Double orgPrice = 0.0;
		double[] p = new double[typeList.size()];//价格数组
		for(int j=0; j<typeList.size(); j++) {
			//商品类型（1.课程 2.章节3.vip卡4商品）
			if("1".equals(typeList.get(j))) {
				WfCourseInfoEntity courseInfo = courseInfoService.queryObjectIgnoreStatus(Integer.valueOf(foreignIdList.get(j)));
				double activityprice = Double.valueOf(courseInfo.getActivityprice());
				if(2==memberCoupons.getLimits() && memberCoupons.getValueIds().contains(foreignIdList.get(j))) {
					p[j] = activityprice;
				}else{
					p[j] =  0;
				}
				orgPrice = orgPrice + p[j];
			}else if("2".equals(typeList.get(j))){
				WfCourseChapterEntity courseChapter = courseChapterService.queryObjectIgnoreStatus(Integer.valueOf(foreignIdList.get(j)));
				double activityprice = Double.valueOf(courseChapter.getChapterprice());
				if(3==memberCoupons.getLimits() && memberCoupons.getValueIds().contains(foreignIdList.get(j))) {
					p[j] = activityprice;
				}else{
					p[j] =  0;
				}
				orgPrice = orgPrice + p[j];
			}else if("3".equals(typeList.get(j))){
				WfVipCardEntity vipCard = vipCardService.queryObject(Integer.valueOf(foreignIdList.get(j)));
				double activityprice = Double.valueOf(vipCard.getCardprice());
				if(4==memberCoupons.getLimits() && memberCoupons.getValueIds().contains(foreignIdList.get(j))) {
					p[j] = activityprice;
				}else{
					p[j] =  0;
				}
				orgPrice = orgPrice + p[j];
			}
		}
		//获取优惠券抵扣数组（按比例分），保留两位小数
		BigDecimal couponsArr[] = new BigDecimal[typeList.size()];
		Double percent = 0.00;
		BigDecimal price =BigDecimal.ZERO;
		for(int i=0; i<typeList.size(); i++){
			price =BigDecimal.valueOf(memberCoupons.getCost());
			percent = p[i]/orgPrice;
			percent = (double)Math.round(percent*100000000)/100000000;
			price = price.multiply(BigDecimal.valueOf(percent)).setScale(2,BigDecimal.ROUND_HALF_UP);
			couponsArr[i] = price;
		}
		return  couponsArr;
	}

	public static List strToList(String type){

		String[] typeArr = type.split(",");
		List<String> typeList1 = Arrays.asList(typeArr);//数组转为list
		List<String> typeList = new ArrayList(typeList1);

		return typeList;
	}

	//查询老铜钱总值（邀请人消费后赠送的）
	public static BigDecimal getAllOldCoin(List<WfCoinLogEntity> coinLogList){
		BigDecimal coins = BigDecimal.ZERO;
		//获取原铜钱总数
		for (int k = 0; k < coinLogList.size(); k++) {
			WfCoinLogEntity coinLogEntity = coinLogList.get(k);
			if (1 == coinLogEntity.getFlowflag() && coinLogEntity.getDeleteflag() == 0) {
				coins = coins.add(coinLogEntity.getCoinvalue());
			} else if (2 == coinLogEntity.getFlowflag() && coinLogEntity.getDeleteflag() == 0
					&& (coinLogEntity.getStatus() == 1 || coinLogEntity.getStatus() == 2)) {
				coins = coins.subtract(coinLogEntity.getCoinvalue());
			}
		}
		return coins;
	}

	//查询新铜钱总值（邀请人消费后赠送的）
	public static BigDecimal getAllNewCoin(List<WfMemberGiveCoinLogEntity> memberberGiveCoinLogList){
		BigDecimal mycoins = BigDecimal.ZERO;
		for (int k = 0; k < memberberGiveCoinLogList.size(); k++) {
			WfMemberGiveCoinLogEntity memberberGiveCoinLog = memberberGiveCoinLogList.get(k);
			if (1 == memberberGiveCoinLog.getType() || 3 == memberberGiveCoinLog.getType()) {
				mycoins = mycoins.add(memberberGiveCoinLog.getCoinvalue());
			} else if (2 == memberberGiveCoinLog.getType()
					&& (memberberGiveCoinLog.getStatus() == 1 || memberberGiveCoinLog.getStatus() == 2)) {
				mycoins = mycoins.subtract(memberberGiveCoinLog.getCoinvalue());
			}
		}
		return mycoins;
	}

	//查询金币总值
	public static BigDecimal getAllGold(List<WfMemberGoldLogEntity> memberGoldLogList){
		BigDecimal mycoins = BigDecimal.ZERO;
		for (int n = 0; n < memberGoldLogList.size(); n++) {
			WfMemberGoldLogEntity memberGold = memberGoldLogList.get(n);
			if (1 == memberGold.getType() || 3 == memberGold.getType()) {
				mycoins = mycoins.add(memberGold.getGoldvalue());
			} else if (2 == memberGold.getType()
					&& (memberGold.getStatus() == 1 || memberGold.getStatus() == 2)) {
				mycoins = mycoins.subtract(memberGold.getGoldvalue());
			}
		}
		return mycoins;
	}

	//查询金币总值
	public static BigDecimal getAllNewGold(List<WfMemberNewGoldLogEntity> memberNewGoldLogList){
		BigDecimal mycoins = BigDecimal.ZERO;
		for (int n = 0; n < memberNewGoldLogList.size(); n++) {
			WfMemberNewGoldLogEntity memberNewGold = memberNewGoldLogList.get(n);
			if (1 == memberNewGold.getType() || 3 == memberNewGold.getType()) {
				mycoins = mycoins.add(memberNewGold.getGoldvalue());
			} else if (2 == memberNewGold.getType()
					&& (memberNewGold.getStatus() == 1 || memberNewGold.getStatus() == 2)) {
				mycoins = mycoins.subtract(memberNewGold.getGoldvalue());
			}
		}
		return mycoins;
	}

	/**
	 * 获取设备信息
	 */
	@RequestMapping("/getDevice")
	@ResponseBody
	@IgnoreToken
	public R getDevice(HttpServletRequest req) {
		String userAgent = req.getHeader("User-Agent");
		Pattern pattern = Pattern.compile(";\\s?(\\S*?\\s?\\S*?)\\s?(Build)?/");
		Matcher matcher = pattern.matcher(userAgent);
		String model = null;
		if (matcher.find()) {
			model = matcher.group(1).trim();
			log.debug("通过userAgent解析出机型：" + model);
		}
		System.out.println(req.getHeader("user-agent"));
		System.out.println("******************************************************");
		if(DeviceUtils.isIOSDevice(req)) {
			System.out.println("---iosApp");//苹果用户来源
		}else if(DeviceUtils.isAndroidDevice(req)){
			System.out.println("---Android");//安卓用户来源
		}else if(DeviceUtils.isWeChat(req)) {
			System.out.println("---wxH5");
		}else{
			System.out.println(req.getHeader("user-agent"));
		}
		return R.ok();
	}

	//生成随机数字和字母,
	public String getStringRandom(int length) {

		String val = "";
		Random random = new Random();

		//参数length，表示生成几位随机数
		for(int i = 0; i < length; i++) {

			/*String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";*/
			//输出字母还是数字
			/*if( "char".equalsIgnoreCase(charOrNum) ) {*/
			//输出是大写字母还是小写字母
			/*int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;*/
			int temp = 65;
			val += (char)(random.nextInt(26) + temp);
			/*} else if( "num".equalsIgnoreCase(charOrNum) ) {
				val += String.valueOf(random.nextInt(10));
			}*/
		}
		return val;
	}


	//提交订单时，总价校验
	/*public int validatePrice(List<String> typeList, List<String> foreignIdList,Double price) {
		//统计所有课程原价的总价
		Double orgPrice = 0.0;
		int access = 1;
		double[] p = new double[typeList.size()];//价格数组
		for (int j = 0; j < typeList.size(); j++) {
			//商品类型（1.课程 2.章节3.vip卡4商品）
			if ("1".equals(typeList.get(j))) {
				WfCourseInfoEntity courseInfo = courseInfoService.queryObjectIgnoreStatus(Integer.valueOf(foreignIdList.get(j)));
				double activityprice = Double.valueOf(courseInfo.getActivityprice());
				p[j] = activityprice;
				orgPrice = orgPrice + activityprice;
			} else if ("2".equals(typeList.get(j))) {
				WfCourseChapterEntity courseChapter = courseChapterService.queryObjectIgnoreStatus(Integer.valueOf(foreignIdList.get(j)));
				double activityprice = Double.valueOf(courseChapter.getChapterprice());
				p[j] = activityprice;
				orgPrice = orgPrice + activityprice;
			} else if ("3".equals(typeList.get(j))) {
				WfVipCardEntity vipCard = vipCardService.queryObject(Integer.valueOf(foreignIdList.get(j)));
				double activityprice = Double.valueOf(vipCard.getCardprice());
				p[j] = activityprice;
				orgPrice = orgPrice + activityprice;
			}
		}
		if(!price.equals(orgPrice)){
			access = -1;
		}
		return access;
	}*/

}
